使用粘贴并与R中的引号组合替换 [英] Using paste and substitute in combination with quotation marks in R
问题描述
请注意,我已经看过这和 但仍然无法解决我的问题。
假设一个最简单的工作示例:
a <-c(1,2,3)
b <-c(2,3,4)
c <-c(4,5,6)$ b $ (d,b,c)
foo< - 函数(x,y,data = data){
data [,c(x ,y)]
}
foo(a,b,data = dftest)
在这里,最后一行显然会返回一个错误:未定义的列被选中
。返回此错误是因为要选择的列是 x
和 y
,它们不是数据框的一部分 dftest
。
问题:如何制定函数的定义以获得所需的输出,即
> dftest [,c(a,b)]
#ab
#1 1 2
#2 2 3
#3 3 4
我想通过调用函数 foo
来获得。
请注意,为了使解决方案对我的目的有用,函数调用格式 foo
被认为是固定的,即只对函数本身做出改变,而不是调用。即 foo(a,b,data = dftest)
是唯一允许的输入。
与 eval
结合使用粘贴
和替换
到第一个用函数调用的参数替换 x
和 y
,然后评估调用。但是,转义引号在这里似乎是一个问题:
foo < - function(x,y,data = data ){
substitute(data [,paste(c(\,x,\,\,y,\),sep =)])
foo(a,b,data = dftest)
eval(foo(a,b,data = dftest))
$ b 这里, foo(a,b,data = dftest)
返回:
dftest [,paste(c(\,a,\,\,b,\)),sep然而,当使用 eval()来评估时, code>(仅限于粘贴
部分),
paste(c(\,a,\,\,b,\),sep =)
pre>
返回:
#c(\1 \2 \)c(\2 \,\3 \)c(\3 \,\4 \ )
而不是,因为我希望 c(a ,b)
,因此再次如上所述的错误。
解决方案试试这个:
<$ (x,y,data = data){
x< - deparse(substitute(x))
y< - deparse(substitute( y))
data [,c(x,y)]
}
Please note that I already had a look at this and that but still cannot solve my problem.
Suppose a minimal working example:
a <- c(1,2,3)
b <- c(2,3,4)
c <- c(4,5,6)
dftest <- data.frame(a,b,c)
foo <- function(x, y, data = data) {
data[, c("x","y")]
}
foo(a, b, data = dftest)
Here, the last line obviously returns an Error: undefined columns selected
. This error is returned because the columns to be selected are x
and y
, which are not part of the data frame dftest
.
Question: How do I need to formulate the definition of the function to obtain the desired output, which is
> dftest[, c("a","b")]
# a b
# 1 1 2
# 2 2 3
# 3 3 4
which I want to obtain by calling the function foo
.
Please be aware that in order for the solution to be useful for my purposes, the format of the function call of foo
is to be regarded fixed, that is, the only changes are to be made to the function itself, not the call. I.e. foo(a, b, data = dftest)
is the only input to be allowed.
Approach: I tried to use paste
and substitute
in combination with eval
to first replace the x
and y
with the arguments of the function call and then evaluate the call. However, escaping the quotation marks seems to be a problem here:
foo <- function(x, y, data = data) {
substitute(data[, paste("c(\"",x,"\",\"",y,"\")", sep = "")])
}
foo(a, b, data = dftest)
eval(foo(a, b, data = dftest))
Here, foo(a, b, data = dftest)
returns:
dftest[, paste("c(\"", a, "\",\"", b, "\")", sep = "")]
However, when evaluating with eval()
(focusing only on the paste
part),
paste("c(\"", a, "\",\"", b, "\")", sep = "")
returns:
# "c(\"1\",\"2\")" "c(\"2\",\"3\")" "c(\"3\",\"4\")"
and not, as I would hope c("a","b")
, thus again resulting in the same error as above.
Try this:
foo <- function(x, y, data = data) {
x <- deparse(substitute(x))
y <- deparse(substitute(y))
data[, c(x, y)]
}
这篇关于使用粘贴并与R中的引号组合替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!