新的
就像列一样吗?
dplyr
1.0.0 版本使得 处理行更加容易。
across
允许对整个列应用函数,可用 dplyr
动词 选择列,例如 sort
和 everything()
:set.seed(1)
df <- as.data.frame(matrix(sample.int(5, 25, TRUE), 5, 5))
df
V1 V2 V3 V4 V5
1 1 3 5 5 5
2 4 2 5 5 2
3 1 3 2 1 2
4 2 3 2 1 1
5 5 1 1 5 4
df %>% mutate(across(everything(),sort))
V1 V2 V3 V4 V5
1 1 1 1 1 1
2 1 2 2 1 2
3 2 3 2 5 2
4 4 3 5 5 4
5 5 3 5 5 5
同样地,我希望能够在选定的行中应用函数,利用更新的 rowwise
dplyr
功能,在不转置数据框的情况下实现。
我找到的最近的解决方案使用了 c_across
:
df %>% rowwise %>%
mutate(sortlist = list(sort(c_across(everything())))) %>%
unnest_wider(sortlist)
# A tibble: 5 x 10
V1 V2 V3 V4 V5 ...1 ...2 ...3 ...4 ...5
<int> <int> <int> <int> <int> <int> <int> <int> <int> <int>
1 1 3 5 5 5 1 3 5 5 5
2 4 2 5 5 2 2 2 4 5 5
3 1 3 2 1 2 1 1 2 2 3
4 2 3 2 1 1 1 1 2 2 3
5 5 1 1 5 4 1 1 4 5 5
但是是否有一种dplyr
的方法可以直接到达:
V1 V2 V3 V4 V5
1 1 3 5 5 5
2 2 2 4 5 5
3 1 1 2 2 3
4 1 1 2 2 3
5 1 1 4 5 5
就像列一样吗?
dplyr
已经让行操作变得容易,但我认为它仍不是处理逐行操作的最佳工具。 - Ronak Shah