R的新手。如何在R中组合这两个表,所以我有两行和三列:
> table8
rchildF
No, not at all rude Yes, somewhat rude Yes, very rude
114 284 286
> table9
rbabyF
No, not at all rude Yes, somewhat rude Yes, very rude
473 148 63
另外,我如何将每个值转换为按行计算的总数的百分比(总计为684)。
答案 0 :(得分:2)
您可以使用merge
merged <- merge(table8, table9, all = TRUE)
# No, not at all rude Yes, somewhat rude Yes, very rude
#1 114 284 286
#2 473 148 63
对于百分比,请使用round
和rowSums
percentages <- round(merged/rowSums(merged), 2) * 100
# No, not at all rude Yes, somewhat rude Yes, very rude
#1 17 42 42
#2 69 22 9
答案 1 :(得分:0)
您可以使用dplyr::bind_rows
:
library(dplyr)
table8 <- read.table(text = "'No, not at all rude' 'Yes, somewhat rude' 'Yes, very rude'
114 284 286", header = T)
table9 <- read.table(text = "'No, not at all rude' 'Yes, somewhat rude' 'Yes, very rude'
473 148 63", header = T)
bind_rows(table8, table9) %>%
transmute(
not_rude = No..not.at.all.rude/rowSums(.[1:3]),
some_rude = Yes..somewhat.rude/rowSums(.[1:3]),
rude = Yes..very.rude/rowSums(.[1:3])
)
not_rude some_rude rude
1 0.1666667 0.4152047 0.41812865
2 0.6915205 0.2163743 0.09210526
答案 2 :(得分:0)
R base也完成了这项工作。尝试
# row-binding data frame
df <- rbind.data.frame(table8, table9)
# No..not.at.all.rude Yes..somewhat.rude Yes..very.rude
#1 0.1666667 0.4152047 0.41812865
#2 0.6915205 0.2163743 0.09210526
# Percentage values
df/rowSums(df)
# No..not.at.all.rude Yes..somewhat.rude Yes..very.rude
#1 0.1666667 0.4152047 0.41812865
#2 0.6915205 0.2163743 0.09210526
#OR
as.data.frame(apply(df/rowSums(df), 2, scales::percent))
# No..not.at.all.rude Yes..somewhat.rude Yes..very.rude
#1 16.7% 41.5% 41.8%
#2 69.2% 21.6% 9.2%