deparse(substitute(x)) in lapply

纵然是瞬间 提交于 2019-12-25 09:19:15

问题


I'm trying to create a column in multiple data frames that contain the name of the dataframe. This is so when they are appended I know where they came from. This is easy to do manually for each dataframe:

# create some example data that need joining
Pb = c(5, 6, 4, 5, 7)
depth = c(1, 2, 3, 4, 5)
df1 <- data.frame(Pb, depth)
df2 <- df1 - 0.5

# add a column to each with the name of the original dataframe
df1$label <- deparse( substitute(df1) )
df2$label <- deparse( substitute(df2) )

Produces the desired output:

> df1
  Pb depth label
1  5     1   df1
2  6     2   df1
3  4     3   df1
4  5     4   df1
5  7     5   df1
> df2
   Pb depth label
1 4.5   0.5   df2
2 5.5   1.5   df2
3 3.5   2.5   df2
4 4.5   3.5   df2
5 6.5   4.5   df2

I'm trying to create a function that will accept a list of dataframes and do the same, but I'm struggling using deparse(substitute(x)) in lapply. My (not working) code below:

label_tool = function(list) {    
addlabels = function(x){ x$labels<-deparse(substitute(x)) }
list <- lapply( list, addlabels )   
return(df)
}

# example usage (see above)
list <- list( df1, df2 )
list <- label_tool(list)

I see others have managed to use deparse(substitute(x)) in lapply, but frankly, I don't understand how. Can anyone help?

来源:https://stackoverflow.com/questions/41897684/deparsesubstitutex-in-lapply

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!