df <- data.frame(Row = c("r_1", "r_2",etc.),
Col = c("Col1", "Col2",etc.),
Value = c(1, 2, etc.))
row_names <- unique(df$Row)
col_names <- unique(df$Col)
#this will give you all possible combinations
combinations <- expand.grid(Row = row_names, Col = col_names)
result <- df %>% group_by(Row, Col) %>% summarize(Value = sum(Value))
result <- left_join(combinations, result, by = c("Row" = "Row", "Col" = "Col"))
result[is.na(result)] <- 0
names(result)[1] <- "R"# choose the value that suits you best
names(result)[2] <- "C"# choose the value that suits you best
library(dplyr)
library(tidyr)
rn <- c("name1", "name2", "name3",
"name1", "name2", "name3") # necessary as duplicate names are not allowed in data.frame
# and will be dropped at type cast
matrix(1:18, ncol=3) %>%
`colnames<-`(c("name1", "name2", "name3")) %>%
`rownames<-`(rn) %>% # here is the sample matrix
# alike one from your question ready for analysis
data.frame() %>%
mutate(rn = rn, .before=1) %>%
# restore the row names
# you can store them from your matrix in a variable before type cast
pivot_longer(-rn) %>%
group_by(rn, name) %>%
summarise(value=sum(value)) %>%
pivot_wider()
2条答案
按热度按时间nhhxz33t1#
你可以这样做。也可以看到代码中的注解。你还需要Grothendieck在他/她的答案中给出的pckgs。
5f0d552i2#
以下是一个完整的单管道tidyverse解决方案:
这将导致: