Access Column Names

If i do

lapply(dataframe, function(x) { column.name <- #insert code here }) 

How do I access the column name that the binding function is currently processing? I want to assign a column name to a variable, column.name, as indicated in the code. Just to clarify, yes, column.name will change with every iteration lapply.

+7
r
source share
1 answer

There is actually a way.

 df <- data.frame(a = 1:2, b = 3:4, c = 5:6) lapply(df, function(x) names(df)[substitute(x)[[3]]]) $a [1] "a" $b [1] "b" $c [1] "c" 

But this should be used as a last resort. Instead use something like (another option is given in the comments)

 lapply(seq_along(df), function(x) names(df[x])) [[1]] [1] "a" [[2]] [1] "b" [[3]] [1] "c" 
+6
source share

All Articles