问题
I am trying to use apply and a user defined function on a data.frame. Inside the function I would like to use the column name (for a title of a plot), but apply seems to strips the column name and passes only a vector. MWE:
trialData <- data.frame('a' = rnorm(100),
'b' = rnorm(100),
'c' = rnorm(100))
someData <- function(dataInput){
return(colnames(dataInput))
}
dataOutput <- apply(trialData, 2, someData)
print(dataOutput)
returns NULL
. Is there any way of accessing the column name inside the function?
回答1:
Thanks to the commentors I arrived at the below which give me my desired result.
trialData <- data.frame('a' = rnorm(100),
'b' = rnorm(100),
'c' = rnorm(100))
someData <- function(dataInput){
# lots of code here
return(
dataName = colnames(dataInput)
)
}
dataOutput <- lapply(colnames(trialData), function(x){someData(trialData[x])})
print(dataOutput)
来源:https://stackoverflow.com/questions/42250209/colnames-passed-through-an-apply-function-r