함수 f에 대한 첫 번째 호출은 작동하지만 두 번째 호출은 작동하지 않습니다. 어떻게 함수를 기대할 수 있도록 함수 f에 문자열 ("v")을 전달할 수 있습니까? 내가 사용 좋아하지 않기 때문에 내가 dt
에 t
에서 전환변수를 예상하는 함수에 문자열을 매개 변수로 전달하는 방법
library(data.table)
library(purrr)
dat <- data.table(v="a")
f <- function(dt, x) {
# first, see if 'x' is a variable holding a string with a column name
seval <- safely(eval)
res <- seval(x, dt, parent.frame())
# if it is, then get the value, otherwise substitute() it
if ((!is.null(res$result)) && inherits(res$result, "character")) {
y <- res$result
} else {
y <- substitute(x)
}
# if it's a bare name, then we deparse it, otherwise we turn
# the string into name and then deparse it
if (inherits(y, "name")) {
y <- deparse(y)
} else if (inherits(y, "character")) {
y <- deparse(as.name(x))
}
dt[, y, with=FALSE]
}
f(dat,v)
## v
## 1: a
f(dat, "v")
## v
## 1: a
V <- "v"
f(dat, V)
## v
## 1: a
f(dat, VVV)
#> throws an Error
:
library(data.table)
f<-function(t,x) t[,deparse(substitute(x)),with=F]
dat<-data.table(v="a")
f(dat,v)
# v
# 1: a
f(dat,eval(parse(text="v")))
# Error in `[.data.table`(t, , deparse(substitute(x)), with = F) :
# column(s) not found: eval(parse(text = "v"))
'dat [, .SDcols = cols]'처럼'.SDcols'와 함께'dat [, mget (col)]'또는'.SD'와 같이'mget() = "v"'. 동일한 함수 인수에 (열의) * 및 * 기호를 문자 벡터로 사용하는 것은 문제와 모호함을 불러옵니다. – Arun