简体   繁体   中英

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

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

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

 
prueba(datosprov,"positivo")

This should work for 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. The approach below is useful if you want to use bare names instead of strings to select variables in a data.frame .

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)

You can access columns within a dataframe by df[,'colname'] , ie

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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