当列作为字符对象输入时,如何使用 tidyverse select?
How do I use tidyverse select when the column is input as a character object?
我正在尝试创建一个根据函数输入选择列的函数:
f <- function(string) {
quosure <- quo(!!sym(string))
dplyr::select(data, !!quosure)
}
temp <- f("id") # returns " Error in !quosure : invalid argument type"
奇怪的是,这个看起来非常相似的代码似乎有效。
g <- function(string) {
quosure <- quo(!!sym(string))
dplyr::pull(data, !!quosure)
}
temp <- g("id") # Works fine
第一个和第二个函数有什么区别,第一个失败,第二个有效?
我使用 dplyr 版本“0.8.0.1”时效果很好。
library(dplyr)
packageVersion("dplyr")
'0.8.0.1'
data <- data.frame(id= 1:10, othervariable= 11:20)
f <- function(string) {
quosure <- quo(!!sym(string))
dplyr::select(data, !!quosure)
}
temp <- f("id")
temp
id
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
如果您需要从数据框中 select(多个)列,我宁愿这样做
df <- data.frame(id= 1:10, othervariable= 11:20, x= 21:30)
f <- function(data, string) {
data[ , string]
}
temp <- f(data= df, string= c("id", "x"))
temp
id x
1 1 21
2 2 22
3 3 23
4 4 24
5 5 25
6 6 26
7 7 27
8 8 28
9 9 29
10 10 30
我正在尝试创建一个根据函数输入选择列的函数:
f <- function(string) {
quosure <- quo(!!sym(string))
dplyr::select(data, !!quosure)
}
temp <- f("id") # returns " Error in !quosure : invalid argument type"
奇怪的是,这个看起来非常相似的代码似乎有效。
g <- function(string) {
quosure <- quo(!!sym(string))
dplyr::pull(data, !!quosure)
}
temp <- g("id") # Works fine
第一个和第二个函数有什么区别,第一个失败,第二个有效?
我使用 dplyr 版本“0.8.0.1”时效果很好。
library(dplyr)
packageVersion("dplyr")
'0.8.0.1'
data <- data.frame(id= 1:10, othervariable= 11:20)
f <- function(string) {
quosure <- quo(!!sym(string))
dplyr::select(data, !!quosure)
}
temp <- f("id")
temp
id
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 10
如果您需要从数据框中 select(多个)列,我宁愿这样做
df <- data.frame(id= 1:10, othervariable= 11:20, x= 21:30)
f <- function(data, string) {
data[ , string]
}
temp <- f(data= df, string= c("id", "x"))
temp
id x
1 1 21
2 2 22
3 3 23
4 4 24
5 5 25
6 6 26
7 7 27
8 8 28
9 9 29
10 10 30