Colnames 通过 apply 函数传递 R

Les*_*ied 6 r apply

我正在尝试在 data.frame 上使用 apply 和用户定义的函数。在函数内部,我想使用列名称(作为绘图的标题),但 apply 似乎会删除列名称并仅传递一个向量。微量元素:

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)
Run Code Online (Sandbox Code Playgroud)

返回NULL。有什么方法可以访问函数内的列名吗?

Les*_*ied 5

感谢评论者,我到达了下面,这给了我想要的结果。

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)
Run Code Online (Sandbox Code Playgroud)