给你另一个问题。如何自动创建数据框"结果"离开我的起始位置。
例如:我必须选择元素" E3"在其中,并总结相应的数字。
我希望得到像我的数据框"结果"的结果。 E3 - > 100 + 200 + 300 = 600
#starting position
v1 <- c("E1","E2","E3")
v2 <- c("E2","E3",NA)
v3 <- c("E3","E5",NA)
number <- c(100, 200, 300)
test <- data.frame(cbind(v1,v2,v3,number))
#result
index <- c("E1","E2","E3","E5")
total <- c(100, 300, 600, 300)
result <- data.frame(cbind(index,total))
谢谢:)
答案 0 :(得分:2)
试试这个:
library(tidyverse)
test %>%
gather(key = "col", value = "val", -number) %>%
group_by(val) %>%
summarise_if(is.numeric, sum)
# A tibble: 5 x 2
val number
<chr> <dbl>
1 E1 100.
2 E2 300.
3 E3 600.
4 E5 200.
5 NA 600.
答案 1 :(得分:1)
以下是基础R
的解决方案:
M <- cbind(v1=c("E1","E2","E3"),
v2=c("E2","E3",NA),
v3=c("E3","E5",NA))
number <- c(100, 200, 300)
index <- c("E1","E2","E3","E5")
sapply(index, function(x) sum(number[apply(M==x, 1, any)], na.rm=TRUE))
# > sapply(index, function(x) sum(number[apply(M==x, 1, any)], na.rm=TRUE))
# E1 E2 E3 E5
# 100 300 600 200
答案 2 :(得分:1)
我们可以使用aggregate
base R
aggregate(total ~., data.frame(index = unlist(test[1:3]),
total = rep(test$number, each = 3)), sum, na.rm = TRUE)
# index total
#1 E1 100
#2 E2 300
#3 E3 600
#4 E5 300
test <- data.frame(v1,v2,v3,number)