I can't figure out a simple problem of how to call a variable name from a dataframe passed as string( function input).
I have a function defined as:
box_lambda = function(Valuename,data1){
data1[,Valuename]=ifelse(data1[,Valuename]==0,0.000001,data1[,Valuename])
b= boxcox(get(Valuename) ~ Age.Group Sex , data = data1)
lambda <- b$x[which.max(b$y)]
return(lambda)
}
But this doesn't work as I get error:
Error in eval(f): 'list' object cannot be coerced to type 'double'
I tried
data1[[Valuename]]=ifelse(data1[Valuename]]==0,0.000001,data1[[Valuename]])
Any help is appreciated!
CodePudding user response:
First you lost a bracket necessary to address a field:
data1[[Valuename]]
You can also use a seties of other approaches from [here][1] and from [here][2]. For instance you can use:
library(dplyr)
data %>%
filter(!!as.name(Valuename) == 0)
So finally you can use :
data1[[Valuename]][data1[[Valuename]]==0] <-0.000001
This script will replace 0 with epsilon and leave the other values. [1]: https://stackoverflow.com/a/74173690/5043424 [2]: https://stackoverflow.com/a/48219802/5043424