真的遇到了 R 中的一個問題,希望能得到一些幫助。
考慮下表:
| 變數 | 民主黨(MF) | 共和黨人(MF) |
|---|---|---|
| 票數(MI) | 30 . 53 | 40 . 23 |
| 投票(TX) | 64 . 42 | 45 . 25 |
| 票數(COL) | 30 . 59 | 20 . 23 |
| 票數(紐約州) | 64 . 40 | 18. 34 |
我想要一個附加列,以給定的相同 MF 格式匯總上述所有值,因此:
| 變數 | 民主黨(MF) | 共和黨人(MF) |
|---|---|---|
| 票數(MI) | 30 . 53 | 40 . 23 |
| 投票(TX) | 64 . 42 | 45 . 25 |
| 票數(COL) | 30 . 59 | 20 . 23 |
| 票數(紐約州) | 64 . 40 | 18. 34 |
| 全部的 | 188 . 194 | 123 . 105 |
有誰知道一個簡單的方法來做到這一點?我提出了需要徹底檢修桌子的解決方案,而理想情況下我不想要。提前致謝!
樣本資料
df <- structure(list(HOW = structure(c(2L, 4L, 3L, 1L), .Label = c("4", "1", "3", "2"), class = "factor"), Democrats = structure(c("1" = 2L, "2" = 4L, "3" = 3L, "4" = 1L), .Label = c("0 . 0", "1 . 2", "3 . 1", "4 . 6"), class = "factor"), Repubs = structure(c("1" = 2L, "2" = 3L, "3" = 4L, "4" = 1L), .Label = c("0 . 2", "1 . 1", "5 . 2", "5 . 7"), class = "factor")), class = "data.frame", row.names = c(NA, -4L))
uj5u.com熱心網友回復:
一個base解決方案:
df[] <- lapply(df, as.character)
rbind(
df,
c(HOW = "Total", lapply(df[-1], \(x) paste(rowSums(sapply(strsplit(x, " . "), as.numeric)), collapse = " . ")))
)
# HOW Democrats Repubs
# 1 1 1 . 2 1 . 1
# 2 2 4 . 6 5 . 2
# 3 3 3 . 1 5 . 7
# 4 4 0 . 0 0 . 2
# 5 Total 8 . 9 11 . 12
uj5u.com熱心網友回復:
這是一個dplyr答案。
library(tidyverse)
df <- structure(list(HOW = structure(c(2L, 4L, 3L, 1L), .Label = c("4", "1", "3", "2"), class = "factor"), Democrats = structure(c("1" = 2L, "2" = 4L, "3" = 3L, "4" = 1L), .Label = c("0 . 0", "1 . 2", "3 . 1", "4 . 6"), class = "factor"), Repubs = structure(c("1" = 2L, "2" = 3L, "3" = 4L, "4" = 1L), .Label = c("0 . 2", "1 . 1", "5 . 2", "5 . 7"), class = "factor")), class = "data.frame", row.names = c(NA, -4L))
df2 <- df %>%
separate(Democrats, c("Democrats.M", "Democrats.F")) %>%
separate(Repubs, c("Repubs.M", "Repubs.F")) %>%
mutate(across(-HOW, as.integer))
df2 %>%
summarize(HOW = "Total", across(-HOW, sum)) %>%
bind_rows(df2, .) %>%
unite("Democrats", starts_with("Democrats."), sep = " . ") %>%
unite("Repubs", starts_with("Repubs."), sep = " . ")
但老實說,我建議將資料保存在單獨的列中,并且只在最后合并顯示。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/480422.html
上一篇:R:所有以開頭的列的總和
