How to use variable labels in R?

杀马特。学长 韩版系。学妹 提交于 2019-12-11 07:27:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!