1)通過Fruit
和Crate
然後首先骨料使用ave
與prop.table
獲得每個水果的比例在箱子:
ag <- aggregate(Mass ~ Fruit + Crate, data, sum)
tr <- transform(ag, percent = 100 * ave(Mass, Crate, FUN = prop.table))
捐贈:
> tr
Fruit Crate Mass percent
1 Apple A 4.0 54.05405
2 Banana A 3.4 45.94595
3 Orange B 2.0 100.00000
4 Apple C 6.6 56.89655
5 Banana C 5.0 43.10345
6 Apple D 1.3 16.45570
7 Orange D 6.6 83.54430
8 Apple E 2.0 34.48276
9 Banana E 1.8 31.03448
10 Orange E 2.0 34.48276
或圖形:
library(ggplot2)
ggplot(tr, aes(Crate, percent, fill = Fruit)) +
geom_bar(stat = "identity") +
scale_fill_manual(values = c("red", "yellow", "orange"))
使用dplyr遵循類似的邏輯可替代
library(magrittr)
data %>%
do(aggregate(Mass ~ Fruit + Crate, ., sum)) %>%
transform(percent = 100 * ave(Mass, Crate, FUN = prop.table))
2)和這裏:
1A)這也可以在一個magrittr管道來表示這樣
library(dplyr)
data %>%
group_by(Crate, Fruit) %>%
summarize(Mass = sum(Mass)) %>%
ungroup() %>%
group_by(Crate) %>%
mutate(percent = 100 * prop.table(Mass)) %>%
ungroup()
給出:
# A tibble: 10 x 4
Crate Fruit Mass percent
<fctr> <fctr> <dbl> <dbl>
1 A Apple 4.0 54.05405
2 A Banana 3.4 45.94595
3 B Orange 2.0 100.00000
4 C Apple 6.6 56.89655
5 C Banana 5.0 43.10345
6 D Apple 1.3 16.45570
7 D Orange 6.6 83.54430
8 E Apple 2.0 34.48276
9 E Banana 1.8 31.03448
10 E Orange 2.0 34.48276
3)一個二維佈局可以用xtabs
可得:
xt <- 100 * prop.table(xtabs(Mass ~ Crate + Fruit, data), 1)
給予:
> xt
Fruit
Crate Apple Banana Orange
A 54.05405 45.94595 0.00000
B 0.00000 0.00000 100.00000
C 56.89655 43.10345 0.00000
D 16.45570 0.00000 83.54430
E 34.48276 31.03448 34.48276
其可容易地在一個曲線圖中顯示這樣的:
plot(xt, col = c("red", "yellow", "orange"),
main = "Proportion of Mass of Fruit per Crates")
給出:
二維佈局可以重整爲長格式與ftable
:
ftable(xt, row.vars = 1:2)
,並提供:
Crate Fruit
A Apple 54.05405
Banana 45.94595
Orange 0.00000
B Apple 0.00000
Banana 0.00000
Orange 100.00000
C Apple 56.89655
Banana 43.10345
Orange 0.00000
D Apple 16.45570
Banana 0.00000
Orange 83.54430
E Apple 34.48276
Banana 31.03448
Orange 34.48276
注1:的代碼中的問題的兩行可以使用如下公式符號來書寫:
aggregate(Mass ~ Crate, data, sum)
aggregate(Mass ~ Fruit + Crate, data, sum)
注2:輸入在再現的形式使用是:
Lines <- "Fruit Crate Mass
Apple A 4
Banana A 3.4
Orange B 2
Apple C 2.1
Apple C 4.5
Banana C 5
Orange D 1
Apple D 1.3
Orange D 2.4
Orange D 3.2
Orange E 2
Banana E 1.1
Banana E 0.7
Apple E 2"
data <- read.table(text = Lines, header = TRUE)
什麼'FruitperCrate $ PercentMassOfFruitPerCrate < - FruitperCrate $ X/TotalCrate [FruitperCrate $板條箱中, 「x」]'? – HubertL
請以可複製的形式提供輸入。見[mcve]。在這種情況下,我在答案末尾的註釋中已經爲你做了。 –