gpt4 book ai didi

r - 如何使用 "gather"和 "select"的变量

转载 作者:行者123 更新时间:2023-12-02 01:02:26 25 4
gpt4 key购买 nike

我想将一个文本分配给一个变量,然后在我的管道中使用该变量。我大量使用 gatherselect

在下面的示例中,我希望能够在我的管道代码中使用 x:

library(tidyverse)

mtcars %>% head

mtcars %>%
gather(type, value, mpg:am) %>% head

mtcars %>% select(mpg:am) %>% head

这是我要使用的变量

x <- "mpg:am"

我试过的都没有用

mtcars %>% 
gather(type, value, get(x)) %>% head


mtcars %>%
gather(type, value, !!rlang::sym(x)) %>% head


mtcars %>% select(x) %>% head
mtcars %>% select(!!rlang::sym(x)) %>% head

有什么想法吗?

最佳答案

我们可以quote/quo它,然后用!!进行评估

x <- quo(mpg:am)
out1 <- mtcars %>%
gather(type, value, !! x)

检查输出

out2 <- mtcars %>%
gather(type, value, mpg:am)
identical(out1, out2)
#[1] TRUE

关于r - 如何使用 "gather"和 "select"的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49727175/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com