Accessing lapply column names

r

Solution

There is a way, actually.

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 that should be used as a last resort. Instead, use something like (another option is given in comments)

lapply(seq_along(df), function(x) names(df[x]))
[[1]]
[1] "a"

[[2]]
[1] "b"

[[3]]
[1] "c"

Problem

If I am doing ``` lapply(dataframe, function(x) { column.name <- #insert code here }) ``` How would I be able to access the name of the column that the lapply function is currently processing? I want to assign the name of the column to a variable, column.name, as indicated in the code. Just to clarify, yes, column.name WILL change with each iteration of the lapply.

Original source

Related problems