什么是使用dplyr的方法来对一些列应用rowwise
函数。例如,我想抓取所有V,
列,并基于行总和将它们转换为百分比。我展示了如何在base中实现它。那么在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}$")))
x %>% rowwise() %>% select(matches("^.{2}$")) %>% props %>% cbind(x[1], .)
?但后半部分并不完全是dplyr。 - Rich ScrivenrowSums
吗?像这样:props <- function(x, y) round(x/y, 2) ; x %>% mutate(Total = rowSums(.[-1])) %>% mutate_each(funs(./Total), -c(A, Total))
。虽然rowSums
和rowwise
都可能效率低下。如果没有NA,我会选择Reduce(`+`, .[-1]))
。 - David Arenburg