Colnames passed through an apply function R

蹲街弑〆低调 提交于 2020-01-25 19:15:13

问题


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

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