Sample Data
I have a list of data frames with two columns each: 1. variable names, 2. integers.
df3 <- df2 <- df1 <- data.frame(Variable = LETTERS[1:5], Value = sample(10:20, 5, replace = TRUE))
df.list <- list(df1 = df1, df2 = df2, df3 = df3)
df.list
# $df1
# Variable Value
# 1 A 17
# 2 B 16
# 3 C 16
# 4 D 18
# 5 E 10
#
# $df2
# Variable Value
# 1 A 17
# ...
What I Want to Do
Each data frame in the list is named. I want to extract the name of the data frame and use it to rename the second column in that data frame:
# $df1
# Variable df1
# 1 A 17
# 2 B 16
# 3 C 16
# 4 D 18
# 5 E 10
#
# $df2
# Variable df2
# 1 A 17
# ...
What I've Tried
I've written a function to do this using deparse(substitute()
and regular expression pattern matching via sub()
:
mod.name <- function(x) {
nx <- deparse(substitute(x))
ny <- sub(".*\\$", "", nx)
names(x)[2] <- ny
x
}
When tested on a single data frame in the list, it works:
mod.name(df.list$df3)
df.list$df3
# Variable df3
# 1 A 17
# 2 B 16
# 3 C 16
# 4 D 18
# 5 E 10
However, when using lapply
to do it on all the data frames in the list, it does not:
lapply(df.list, mod.name)
df.list
# $df1
# Variable X[[i]]
# 1 A 17
# 2 B 16
# 3 C 16
# 4 D 18
# 5 E 10
#
# $df2
# Variable X[[i]]
# 1 A 17
# ...
Of course, the issue of using deparse(substitute()
with lapply()
has been discussed before on StackOverflow, but I could not get any of the solutions here, here, or here to work for me.