gpt4 book ai didi

r - 更改 data.table 中列名大小写的最有效方法是什么?

转载 作者:行者123 更新时间:2023-12-01 12:45:26 24 4
gpt4 key购买 nike

有时在合并之前更改列名的大小写以保持一致性很有用。使用 data.frame 时,这非常简单(如 here 所述);尽管相同的解决方案适用于 ``data.table`,但它会引发警告。例如,

ran <- rep(34,50)
dom <- rep("cat",50)
table <- rep("pig", 50)

DT <- data.table(ran,dom,table); head(DT)
ran dom table
1: 34 cat pig
2: 34 cat pig
3: 34 cat pig
4: 34 cat pig
5: 34 cat pig
6: 34 cat pig

##the data.frame way

names(DT) <- toupper(names(DT))

##the error
Warning message:
In `names<-.data.table`(`*tmp*`, value = c("RAN", "DOM", "TABLE" :
The names(x)<-value syntax copies the whole table. This is due to <- in R
itself. Please change to setnames(x,old,new) which does not copy and is faster.
See help('setnames'). You can safely ignore this warning if it is inconvenient
to change right now. Setting options(warn=2) turns this warning into an error,
so you can then use traceback() to find and change your names<- calls.

我已经使用以下解决方法来避免错误,并且它在宽数据集上的速度要快得多,但是是否有 data.table 方法可以做到这一点?

##the work around
upper <- toupper(names(DT))

setnames(DT,upper);head(DT)

RAN DOM TABLE
1: 34 cat pig
2: 34 cat pig
3: 34 cat pig
4: 34 cat pig
5: 34 cat pig
6: 34 cat pig

最佳答案

为了给这个答案,正如评论所说,setnames 是一个 data.table 函数并且已经是推荐的 data.table方式(正如来自 data.table 的长警告所建议的那样);例如,

setnames(DT,toupper(names(DT)))

不要与 stats 包中的 setNames 函数混淆! (注意大写 N)。

关于r - 更改 data.table 中列名大小写的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16478614/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com