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?
推荐答案
错误找不到功能get<-
"是R告诉您无法使用<-
更新"got"对象.您可能使用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屋!