如何解决创建使用字符串和变量来调用列的函数-使用基R和dplyr
我需要一些帮助来了解评估在我编写的函数中是如何工作的:
该函数将执行两项操作,其中涉及列“ id”(其名称由用户提供)以及其他一些省略的事情:
possible_matches <- function(i,df,id){
k1 <- df$j[df$id == df$id[i]]
df3 <- df%>%
mutate(index = {{id}})
list(df3,k1)
}
如您所见,这将使用两种不同的调用id
的方式-是否有一种简单的方法来统一这两种方法?首先,我已经尝试了第一部分在df[,'id'] == df[i,'id]
的行中写一些东西,但这会产生一个错误,表明无法比较大小不相等的数据帧。
这里是一个例子:
df <- data.frame(V1 = c(1:5,2:6),j = 1:10)
possible_matches(2,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]]
integer(0)
这显然是错误的,因为至少有一行V1
等于df$V1[2]
解决方法
如果id
是未引用的列名
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(2,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
如果我们要使用filter
possible_matches <- function(i,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,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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。