使用apply在每次迭代中获取一个变量名

时间:2016-10-24 13:58:51

标签: r loops apply var lapply

我正在使用带有函数的//Shade rules for all things play: assemblyShadeRules in assembly := Seq( ShadeRule.rename("play.api.**" -> "shade.play.api.@1").inAll ) //Grabbed from the "publishing" section of the sbt-assembly readme, excluding the "assembly" classifier addArtifact(artifact in (Compile, assembly), assembly) // Only the play stuff and the "S" serializers need to be shaded since they use/introduce play: assemblyExcludedJars in assembly := { val cp = (fullClasspath in assembly).value val toIncludeInPackage = Seq( "play-json_2.11-2.3.8.jar", "play-datacommons_2.11-2.3.8.jar", "play-iteratees_2.11-2.3.8.jar", "play-functional_2.11-2.3.8.jar", "S_2.11-0.0.0.jar" ) cp filter {c => !toIncludeInPackage.contains(c.data.getName)} } ,但是,我不是在每次迭代中只得到变量的一个名称,而是从我的数据集中获取每个变量名。

lapply()

我得到了这个输出:

colnames(data) <- c("var1", "var2")

varnames <- function(var, name){
   return(name)
}

print(lapply(data, varnames, name=names(data)))

但是,我想得到:

$var1
[1] "var1" "var2"

$var2
[1] "var1" "var2"

1 个答案:

答案 0 :(得分:0)

您在此处在代码中指定的内容是:

lapply(data, varnames, name=names(data))

循环遍历data的列,并为函数name提供其他变量varnames。请注意,此处代码不会迭代name,而是按原样传递。

如果您想获得所需的输出,可以使用mapply。这本质上是lapply的一个版本,它允许迭代多个变量:

mapply(varnames, data, names(data)) 
  var1   var2 
"var1" "var2" 

要对每个列执行某些操作,并且仍以某种方式保留名称,我会使用dplyr(因为您不完全清楚您的最终目标是什么,我猜这个是你在哪里之后):

library(dplyr)
data = data.frame(var1 = runif(10), var2 = runif(10), 
                  var3 = runif(10), var4 = runif(10))
data %>% summarise_each(funs(mean, sd, median), var1:var4)
  var1_mean var2_mean var3_mean var4_mean   var1_sd   var2_sd  var3_sd
1 0.6063735 0.5308427 0.2872901 0.6043027 0.2586042 0.2303065 0.245709
    var4_sd var1_median var2_median var3_median var4_median
1 0.2721362   0.6814136   0.4535982    0.200493    0.644607

或者使用gather中的tidyr

data %>% 
   gather(variable, value) %>% 
   group_by(variable) %>% 
     summarise_each(funs(mean, sd, median), value)
Source: local data frame [4 x 4]

  variable      mean        sd    median
    (fctr)     (dbl)     (dbl)     (dbl)
1     var1 0.6063735 0.2586042 0.6814136
2     var2 0.5308427 0.2303065 0.4535982
3     var3 0.2872901 0.2457090 0.2004930
4     var4 0.6043027 0.2721362 0.6446070