'How to sum all values of a cell if it corresponds with a specific value in another cell?
I might just be going about it the wrong way, but I'm having trouble pulling out all of the female scores and all of the male scores into their own respective dataframes.
I don't need to have any of the exam information, so really I could just get every 'f' and it's corresponding score and every 'm' and it's corresponding score into a dataframe.
Solution 1:[1]
data <- tribble(~"X",~"Exam1",~"X.1",~"Exam2",~"X.2",
"n","Score","Gender","Score","Gender",
"1","45","m","66","f",
"2","60","f","73","m")
# Create informative column names
Colnames <- colnames(data) %>% str_c(.,dplyr::slice(data,1) %>% unlist,sep = "_")
# Set column names
data <- data %>%
setNames(Colnames) %>%
dplyr::slice(-1)
# Arrange data by exam type by first getting exam "number"
colnames(data) %>%
str_extract("\\d|\\d\\d") %>%
str_subset("\\d") %>%
unique %>%
# Split and arrange data by exams
purrr::map_df(~{
data %>%
dplyr::select(matches(str_c("X_n|",.x))) %>%
dplyr::mutate(Exam = str_c("Exam ",.x)) %>%
dplyr::rename_all(~c("Serial number","Exam score","Gender","Exam"))
}) %>%
# Split data by gender
dplyr::group_by(Gender) %>%
dplyr::group_split()
Output:
[[1]]
# A tibble: 2 × 4
`Serial number` `Exam score` Gender Exam
<chr> <chr> <chr> <chr>
1 2 60 f Exam 1
2 1 66 f Exam 2
[[2]]
# A tibble: 2 × 4
`Serial number` `Exam score` Gender Exam
<chr> <chr> <chr> <chr>
1 1 45 m Exam 1
2 2 73 m Exam 2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Anurag N. Sharma |