通过应用函数 R 传递的列名 [英] Colnames passed through an apply function R

查看:23
本文介绍了通过应用函数 R 传递的列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 data.frame 上使用 apply 和用户定义的函数.在函数内部,我想使用列名(用于绘图的标题),但 apply 似乎去除了列名并只传递了一个向量.MWE:

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)

返回NULL.有没有办法访问函数内部的列名?

returns NULL. Is there any way of accessing the column name inside the function?

推荐答案

感谢评论者我到达了下面,他们给了我想要的结果.

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)

这篇关于通过应用函数 R 传递的列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆