Ranon Kahn Ranon Kahn -4 years ago 75
R Question

How to use a column value from another data frame to rename a data frame in R?

I have a list of names in a data frame column as given below. How do I rename an existing data frame using a value from the column?

# New Data Frame Name List

NewDataFrameNameList

DF_Names
1 New_DF_Name1
2 New_DF_Name2
3 New_DF_Name2


Existing data frames

old_DF_Name1
old_DF_Name2
old_DF_Name3


Renaming existing data frame. I tried assign function but, it did not work.

assign(old_DF_Name1, NewDataFrameNameList[1,1])

Answer Source
# 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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download