简体   繁体   English

R 使用列名字符串作为 function 参数来引用列

[英]R use column name string as a function parameter to reference column

I've been trying to calculate the mean of a column in a data.frame inside a function which I pass teh data.frame and the name of the column to calculate but I'm not able to do so我一直在尝试计算 function 内的 data.frame 中的列的平均值,我传递了 data.frame 和要计算的列的名称,但我无法这样做

This is an example of the data这是数据的一个例子

aleatorio<-rnorm(1:52)
cod_prov<-c(1:52)
datosprov<-cbind(cod_prov, aleatorio)
rm(aleatorio,cod_prov)

This is the function这是 function

prueba<-function(bbdd,varmap){
  forMap<-noquote(paste0(substitute(bbdd),"$",substitute(varmap)))
  mean(forMap)
}

 
prueba(datosprov,"positivo")

This should work for data.frames .这应该适用于data.frames As @jay.sf points correctly out in the comments, @Otto Kässis approach is safer since it works on data.frames and matrices.正如@jay.sf 在评论中正确指出的那样,@Otto Kässis 方法更安全,因为它适用于 data.frames 和矩阵。 The approach below is useful if you want to use bare names instead of strings to select variables in a data.frame .如果您想对 data.frame中的select 变量使用裸名而不是字符串,则以下方法很有用。

prueba <- function(bbdd,varmap){
  mean(bbdd[[substitute(varmap)]])
}

prueba(iris, Sepal.Length)
#> [1] 5.843333

Created on 2021-01-08 by the reprex package (v0.3.0)代表 package (v0.3.0) 于 2021 年 1 月 8 日创建

You can access columns within a dataframe by df[,'colname'] , ie您可以通过df[,'colname']访问 dataframe 中的列,即

 prueba<-function(bbdd,varmap){
   forMap<-bbdd[,varmap]
   mean(forMap)
 }

>  prueba(datosprov,"aleatorio")
[1] -0.1167871

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM