为`:=`中的`glue()`提供data.table的环境

问题描述 投票:0回答:1

我想弄清楚是否有一种在 data.table 的

glue()
中使用
j
的好方法:

library(data.table)
library(glue)
data(iris)
dt.iris <- data.table(iris)


dt.iris[, myText := glue('The species is {Species} with sepal length of {Sepal.Length}')] 
# Error in eval(parse(text = text, keep.source = FALSE), envir) : 
#   object 'Species' not found

只要我指出就可以使用

.envir = .SD
:

dt.iris[, myText := glue('The species is {Species} with sepal length of {Sepal.Length}', .envir = .SD)]
# works OK

但我想知道是否可以找到某种方法而不需要每次都添加它。也许是这样的:

glue1 <- function(...) glue(..., .envir = ???) 
r data.table r-glue
1个回答
0
投票

你可以做

gluedt <- function(...) glue::glue(..., .envir = parent.frame(3)$x)

测试,我们有:

library(data.table)

data(iris)
dt.iris <- data.table(iris)
       
dt.iris[, myText := gluedt('The species is {Species} with sepal length of {Sepal.Length}')]

dt.iris
#>      Sepal.Length Sepal.Width Petal.Length Petal.Width   Species
#>   1:          5.1         3.5          1.4         0.2    setosa
#>   2:          4.9         3.0          1.4         0.2    setosa
#>   3:          4.7         3.2          1.3         0.2    setosa
#>   4:          4.6         3.1          1.5         0.2    setosa
#>   5:          5.0         3.6          1.4         0.2    setosa
#>  ---                                                            
#> 146:          6.7         3.0          5.2         2.3 virginica
#> 147:          6.3         2.5          5.0         1.9 virginica
#> 148:          6.5         3.0          5.2         2.0 virginica
#> 149:          6.2         3.4          5.4         2.3 virginica
#> 150:          5.9         3.0          5.1         1.8 virginica
#>                                                 myText
#>   1:    The species is setosa with sepal length of 5.1
#>   2:    The species is setosa with sepal length of 4.9
#>   3:    The species is setosa with sepal length of 4.7
#>   4:    The species is setosa with sepal length of 4.6
#>   5:      The species is setosa with sepal length of 5
#>  ---                                                  
#> 146: The species is virginica with sepal length of 6.7
#> 147: The species is virginica with sepal length of 6.3
#> 148: The species is virginica with sepal length of 6.5
#> 149: The species is virginica with sepal length of 6.2
#> 150: The species is virginica with sepal length of 5.9

创建于 2023-11-11,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.