How to take in text/character argument without quotes

断了今生、忘了曾经 提交于 2019-11-29 23:40:21

问题


Sorry if the question is unclear. Feel free to change it.

So basically I am trying to find a way so that text/character string arguments for a function don't require quotes.

foo  = function(x, y, data){
    n1 = length(data[,x])
    n2 = length(data[,y])
    cat(n1, n1)
 }

If I use the following code

data(survey)
foo(Sex, Fold, survey)

I will get an error message. But if I use the following:

foo("Sex", "Fold", survey)

or

foo(1, 5, survey)

the function will give me what I want. So I wonder if there is any way to construct the function such that I won't need to use quotes around the column names. Thanks!


回答1:


Well, this will work with the symbols:

foo  = function(x,y, data){
    n1 <- length(eval(substitute(x),data))
    n2 <- length(eval(substitute(y),data))
    cat(n1,n2)  
}

If you wanted this to work with quoted variable names and integer indices as well, you could simply check x and y at the start with some simple if-else branching.

But it comes with the standard warning that the eval(substitute()) idiom can be dangerous to use. (You may not always be able to anticipate how it won't work in some cases, and you may not realize when it isn't working.)




回答2:


That has to do with the indices [] argument to a data frame.

When you say DF[,x] it's telling R which column to choose from DF. If x is the literal column "Sex" from DF, it will tell R that you want all the columns that are in the vector DF$Sex.

So if you use "Sex"/"Fold" or 1,5, then your function should be as is. If you want to use Sex and Fold, then your function should be:

foo = function(x,y,data){
n1 <- length(x)
n2 <- length(y)
cat(n1,n2)
}


来源:https://stackoverflow.com/questions/13040120/how-to-take-in-text-character-argument-without-quotes

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