使用dplyrR中的last_col()函数过滤数据框
我有多个看起来像这样的数据框
time <- c(1,1,1,1,2,2,2,2,3,3,3,3)
ID <- c(1,2,3,4,1,2,3,4,1,2,3,4)
value <- c(0,0.1,0.2,0.4,0,0.05,0.05,0.5,0.20,0.40,0.50,0.60)
test <- data.frame(time, ID, value)
test
time ID value
1 1 1 0.00
2 1 2 0.10
3 1 3 0.20
4 1 4 0.40
5 2 1 0.00
6 2 2 0.05
7 2 3 0.05
8 2 4 0.50
9 3 1 0.20
10 3 2 0.40
11 3 3 0.50
12 3 4 0.6
我希望能够根据最后一列中小于 0.05 的值过滤数据框。我知道我可以在 baseR 中轻松使用test[,ncol(test)] <0.05
有没有一种方法可以将其合并到 dplyr 管道中或使用 last_col() 函数,例如:test %>% filter(.,last_col()<0.05)
任何帮助表示赞赏
回答
dplyr >= 1.0.0
使用dplyr::across:
df %>%
dplyr::filter(across(last_col(), ~ . < 0.05))
dplyr < 1.0.0
使用filter_at:
df %>%
dplyr::filter_at(vars(last_col()), ~ . < 0.05)
vars并且last_col也来自dplyr包裹。
- I think the `filter_at` functions are being deprecated. Better get used to `across`