如何使用其他数据框中的列值重命名R中的数据框?

时间:2017-02-27 07:51:39

标签: r

我在数据框列中有一个名称列表,如下所示。如何使用列中的值重命名现有数据框?

# New Data Frame Name List

NewDataFrameNameList

  DF_Names    
1 New_DF_Name1   
2 New_DF_Name2
3 New_DF_Name2

现有数据框

old_DF_Name1
old_DF_Name2
old_DF_Name3

重命名现有数据框。我尝试分配功能但是,它没有用。

assign(old_DF_Name1, NewDataFrameNameList[1,1])

1 个答案:

答案 0 :(得分:1)

# data frame with names
df1 <- data.frame(a = letters[1:2], stringsAsFactors = FALSE)

# data frames whose names have to be renamed
df2 <- data.frame( i = 1:5, j = 6:10 )
df3 <- data.frame( i = 11:15, j = 16:20 )
ls()
# [1] "df1" "df2" "df3"

# get values of data frame and assign it to names in x using mapply
# .GlobalEnv puts the newly created data frames in global environment.
invisible( mapply( function( x, y ) assign( x, y, envir = .GlobalEnv ), 
                   x = c(df1$a), 
                   y = mget( c("df2", "df3" ) ) ) )

ls()
# [1] "a"   "b"   "df1" "df2" "df3"

rm( list = c( "df1", "df2", "df3" ) )
ls()
# [1] "a" "b"

a
#   i  j
# 1 1  6
# 2 2  7
# 3 3  8
# 4 4  9
# 5 5 10

b
#    i  j
# 1 11 16
# 2 12 17
# 3 13 18
# 4 14 19
# 5 15 20