问题
I have a function that takes input as the column name of dataframe as columnname~1
.
The dataframe consists of about 50 columns in which I want to repeat the process, I can
use a for loop to generate column name as a character which unfortunately the function does
not recognize. The difference is just M1~1
(works) vs "M1"~1
Any suggestions are welcome
回答1:
Try:
as.formula(paste("M1","1",sep="~"))
回答2:
Use the "[[ function?
datafrm[[M1]] ~ 1
That function will interpret the character value and convert it to a language value. Or you could use the do.call
function. Best answers will be forthcoming if we have specifics of the dataframe and the function.
回答3:
Or as an alternative to paste you can use sprintf:
variablename = "M1"
as.formula(sprintf("%s ~ 1", variablename))
回答4:
You can also use this:
substitute(columnname~1,list(columnname=as.name("M1")))
EDIT
It will also work when you substitute "M1" with variable containing string (M1 <- "M1").
来源:https://stackoverflow.com/questions/9268154/how-to-use-variable-labels-in-r