假设我有一个数据帧:
> my.df <- data.frame(uid=c(1,1,3),somevalue=c("x","y","z"))
> my.df
uid somevalue
1 1 x
2 1 y
3 3 z
我想要:
uid somevalue
1 1 y
2 3 z
我不能用
distinct(my.df, uid, .keep_all= TRUE)
因为变量名"uid"
可能会更改。但是,我将变量名存储为字符串。
所以我得到了
> iKey <- "uid"
> distinct(my.df, iKey, .keep_all= TRUE)
uid somevalue
1 1 x
2 1 y
3 3 z
Warning message:
Trying to compute distinct() for variables not found in the data:
- `iKey`
This is an error, but only a warning is raised for compatibility reasons.
The operation will return the input unchanged.
如何才能让distinct()使用iKey
的值,而不是从字面上理解它?
发布于 2020-09-24 02:10:44
我们可以使用.data
代词:
library(dplyr)
distinct(my.df, .data[[iKey]], .keep_all= TRUE)
# uid somevalue
#1 1 x
#2 3 z
或者使用sym
将iKey
转换为symbol并对其求值为!!
distinct(my.df, !!sym(iKey), .keep_all= TRUE)
发布于 2020-09-24 03:27:53
tidyselect across
/all_of
习惯用法也适用:
distinct(my.df, across(all_of(iKey)), .keep_all= TRUE)
https://stackoverflow.com/questions/64038559
复制相似问题