A solution using the tidyverse
package. The key is to count the row number tiwce for different group columns, calcualte the percentage, and then spread the data frame.
library(tidyverse)
dat2 <- dat %>%
group_by(choice, g) %>%
add_count() %>%
group_by(choice, g, score) %>%
add_count() %>%
mutate(Percentage = nn/n) %>%
select(-n, -nn) %>%
distinct() %>%
spread(g, Percentage, fill = 0) %>%
select(choice, score, `%g(M)` = M, `%g(F)` = F) %>%
ungroup()
dat2
# # A tibble: 6 x 4
# choice score `%g(M)` `%g(F)`
# <int> <dbl> <dbl> <dbl>
# 1 1 0.1 0.333 0
# 2 1 0.15 0 1
# 3 1 0.2 0.667 0
# 4 2 0.05 0.667 0
# 5 2 0.15 0.333 0
# 6 2 0.2 0 1
Or the following, which is more concise than my previous solution.
dat2 <- dat %>%
count(choice, g, score) %>%
group_by(choice, g) %>%
mutate(Percentage = n/sum(n)) %>%
select(-n) %>%
spread(g, Percentage, fill = 0) %>%
select(choice, score, `%g(M)` = M, `%g(F)` = F) %>%
ungroup()
dat2
# # A tibble: 6 x 4
# choice score `%g(M)` `%g(F)`
# <int> <dbl> <dbl> <dbl>
# 1 1 0.1 0.333 0
# 2 1 0.15 0 1
# 3 1 0.2 0.667 0
# 4 2 0.05 0.667 0
# 5 2 0.15 0.333 0
# 6 2 0.2 0 1
DATA
dat <- read.table(text = "choice g score
1 M .10
1 M .20
1 F .15
1 F .15
1 M .20
2 M .05
2 M .05
2 M .15
2 F .20",
header = TRUE, stringsAsFactors = FALSE)
choice = 1
andscore = 0.10
why is the percentage ofM
0.333
? Can you elaborate on the rules for calculating the percentages. What happens if you have duplicate rows (e.g. forchoice = 1
,g = F
andscore = 0.15
)?