R - 使用 get() 更改列名 [英] R - Change column name using get()
问题描述
我的全局环境中有几个 data.frame
需要合并.许多 data.frame
具有相同的列名称.我想为每一列附加一个后缀,以标记其原始 data.frame
.因为我有很多 data.frame
,所以我想自动化这个过程,如下例所示.
I have several data.frame
s in my Global Environment that I need to merge. Many of the data.frame
s have identical column names. I want to append a suffix to each column that marks its originating data.frame
. Because I have many data.frame
s, I wanted to automate the process as in the following example.
df1 <- data.frame(id = 1:5,x = LETTERS[1:5])
df2 <- data.frame(id = 1:5,x = LETTERS[6:10])
obj <- ls()
for(o in obj){
s <- sub('df','',eval(o))
names(get(o))[-1] <- paste0(names(get(o))[-1],'.',s)
}
# Error in get(o) <- `*vtmp*` : could not find function "get<-"'
但是作业的各个部分都可以正常工作:
But the individual pieces of the assignment work fine:
names(get(o))[-1]
# [1] "x"
paste0(names(get(o))[-1],'.',s)
# [1] "x.1"
我以类似的方式使用 get 将每个对象 write.csv
写入文件.
I've used get in a similar way to write.csv
each object to a file.
for(o in obj){
write.csv(get(o),file = paste0(o,'.csv'),row.names = F)
}
知道为什么在作业中更改列名称不起作用吗?
Any ideas why it's not working in the assignment to change the column names?
推荐答案
could not find function get<-
"的错误是 R 告诉你不能使用 <-
更新一个得到"的对象.您可能可以使用 assign
,但是这段代码已经很难阅读了.更好的解决方案是使用 list
.
The error "could not find function get<-
" is R telling you that you can't use <-
to update a "got" object. You could probably use assign
, but this code is already difficult enough to read. The better solution is to use a list
.
从你的例子:
df1 <- data.frame(id = 1:5,x = LETTERS[1:5])
df2 <- data.frame(id = 1:5,x = LETTERS[6:10])
# put your data frames in a list
df_names = ls(pattern = "df[0-9]+")
df_names # make sure this is the objects you want
# [1] "df1" "df2"
df_list = mget(df_names)
# now we can use a simple for loop (or lapply, mapply, etc.)
for(i in seq_along(df_list)) {
names(df_list[[i]])[-1] =
paste(names(df_list[[i]])[-1],
sub('df', '', names(df_list)[i]),
sep = "."
)
}
# and the column names of the data frames in the list have been updated
df_list
# $df1
# id x.1
# 1 1 A
# 2 2 B
# 3 3 C
# 4 4 D
# 5 5 E
#
# $df2
# id x.2
# 1 1 F
# 2 2 G
# 3 3 H
# 4 4 I
# 5 5 J
现在合并它们也很容易:
It's also now easy to merge them:
Reduce(f = merge, x = df_list)
# id x.1 x.2
# 1 1 A F
# 2 2 B G
# 3 3 C H
# 4 4 D I
# 5 5 E J
有关更多讨论和示例,请参阅如何制作数据框列表?
For more discussion and examples, see How do I make a list of data frames?
这篇关于R - 使用 get() 更改列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!