创建一个同时使用字符串和变量调用列的函数-使用base R和dplyr
我需要一些帮助,以了解评估在我编写的函数中是如何工作的: 该函数将执行两个涉及列“id”的操作,该列的名称由用户提供,以及其他一些省略的内容:创建一个同时使用字符串和变量调用列的函数-使用base R和dplyr,r,dplyr,subset,evaluation,R,Dplyr,Subset,Evaluation,我需要一些帮助,以了解评估在我编写的函数中是如何工作的: 该函数将执行两个涉及列“id”的操作,该列的名称由用户提供,以及其他一些省略的内容: possible_matches <- function(i, df, id){ k1 <- df$j[df$id == df$id[i]] df3 <- df%>% mutate(index = {{id}}) list(df3, k1) } 给我: [[1]] V1 j index
possible_matches <- function(i, df, id){
k1 <- df$j[df$id == df$id[i]]
df3 <- df%>%
mutate(index = {{id}})
list(df3, k1)
}
给我:
[[1]]
V1 j index
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
6 2 6 2
7 3 7 3
8 4 8 4
9 5 9 5
10 6 10 6
[[2]]
integer(0)
这显然是错误的,因为如果
id
是不带引号的列名,那么至少有一行的V1
值等于dodf$V1[2]
possible_matches <- function(i, df, id) {
# // convert the id to string with `as_name` after converting to quosure
idnew <- rlang::as_name(rlang::enquo(id))
# // now we use [[ to subset the column and then specify the i index
k1 <- df$j[df[[idnew]] == df[[idnew]][i]]
df3 <- df%>%
mutate(index = {{id}}) # // curly-curly for quosure + evaluation (!!)
list(df3, k1)
}
如果我们想使用
过滤器
possible_matches <- function(i, df, id) {
to_filter <- df%>%
# // select the column
select({{id}}) %>%
# // slice the row
slice(i) %>%
# // pull the column as vector
pull(1)
k1 <- df %>%
# // now we filter with the value from to_filter
filter({{id}} == to_filter) %>%
pull(j)
df3 <- df%>%
mutate(index = {{id}})
list(df3, k1)
}
possible_matches(2, df, V1)
#[[1]]
# V1 j index
#1 1 1 1
#2 2 2 2
#3 3 3 3
#4 4 4 4
#5 5 5 5
#6 2 6 2
#7 3 7 3
#8 4 8 4
#9 5 9 5
#10 6 10 6
#[[2]]
#[1] 2 6
可能的\u匹配%
#//切片
切片(i)%>%
#//将列作为向量拉入
拉力(1)
k1%
#//现在我们使用值from to\u filter进行筛选
筛选器({{id}}==to_filter)%>%
拉力(j)
df3%
变异(索引={{id}})
列表(df3,k1)
}
可能的_匹配(2,df,V1)
#[[1]]
#v1j指数
#1 1 1 1
#2 2 2 2
#3 3 3 3
#4 4 4 4
#5 5 5 5
#6 2 6 2
#7 3 7 3
#8 4 8 4
#9 5 9 5
#10 6 10 6
#[[2]]
#[1] 2 6
请检查第二部分中的更新是否有办法使用dplyr工具,如中所示?这样做更直观me@ArthurCarvalhoBrito你的意思是创建“k1”部分?我想你已经编辑了答案。但考虑到经过编辑的答案,yes@ArthurCarvalhoBrito早些时候,我没有注意到您想要更改整数(0)
,因为我认为它是预期的。问题在于索引。它应该在评估之外
possible_matches(2, df, V1)
#[[1]]
# V1 j index
#1 1 1 1
#2 2 2 2
#3 3 3 3
#4 4 4 4
#5 5 5 5
#6 2 6 2
#7 3 7 3
#8 4 8 4
#9 5 9 5
#10 6 10 6
#[[2]]
#[1] 2 6
possible_matches <- function(i, df, id) {
to_filter <- df%>%
# // select the column
select({{id}}) %>%
# // slice the row
slice(i) %>%
# // pull the column as vector
pull(1)
k1 <- df %>%
# // now we filter with the value from to_filter
filter({{id}} == to_filter) %>%
pull(j)
df3 <- df%>%
mutate(index = {{id}})
list(df3, k1)
}
possible_matches(2, df, V1)
#[[1]]
# V1 j index
#1 1 1 1
#2 2 2 2
#3 3 3 3
#4 4 4 4
#5 5 5 5
#6 2 6 2
#7 3 7 3
#8 4 8 4
#9 5 9 5
#10 6 10 6
#[[2]]
#[1] 2 6