在某些列上应用函数的dplyr方法是什么?rowwise
例如,我想抓住所有V,
列,然后根据行总和将它们转换为百分比。我将展示如何在基础中执行此操作。在dplyr链中呢?同样也很高兴以data.table的形式看到(尽管这里首选的是dplyr解决方案)。
x <- data.frame(A=LETTERS[1:5], as.data.frame(matrix(sample(0:5, 25, T), ncol=5)))
data.frame(x[1], x[-1]/rowSums(x[-1]))
## A V1 V2 V3 V4 V5
## 1 A 0.1428571 0.2142857 0.2142857 0.35714286 0.07142857
## 2 B 0.2000000 0.2000000 0.1500000 0.20000000 0.25000000
## 3 C 0.3571429 0.2857143 0.0000000 0.07142857 0.28571429
## 4 D 0.1904762 0.2380952 0.1904762 0.23809524 0.14285714
## 5 E 0.2000000 0.2500000 0.1500000 0.25000000 0.15000000
library(dplyr)
props <- function(x) round(x/sum(x), 2)
# does not work
x %>%
rowwise()
mutate(props(matches("^.{2}$")))
您可以结合tidyr的spread
,并gather
与dplyr得到以下单管道:
x <- data.frame(A=LETTERS[1:5], as.data.frame(matrix(sample(0:5, 25, T), ncol=5)))
y <- x %>%
gather(V, val, -A) %>%
group_by(A) %>%
mutate(perc = val / sum(val)) %>%
select(-val) %>%
spread(V, perc)
使用整洁的数据,很容易获得任何按组计算的总和(行,列或任何嵌套的索引级)并计算百分比。在spread
和gather
将让你从你的输入数据格式。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句