Hugo
Hugo

Reputation: 11

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")

Upvotes: 1

Views: 946

Answers (2)

TimTeaFan
TimTeaFan

Reputation: 18561

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)

Upvotes: 2

Otto K&#228;ssi
Otto K&#228;ssi

Reputation: 3083

You can access columns within a dataframe by df[,'colname'], i.e.

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

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

Upvotes: 1

Related Questions