From
x <- read.csv("stats.csv", header = TRUE)
I have two columns:
Gender Score
male 20
female 25
male 10
female 10
How do I add the total Score for just males for example?
From
x <- read.csv("stats.csv", header = TRUE)
I have two columns:
Gender Score
male 20
female 25
male 10
female 10
How do I add the total Score for just males for example?
We can use
library(dplyr)
x %>%
mutate(totalScore = sum(Score[Gender == "male"]))
If the 'female' should be kept as NA
x %>%
mutate(totalScore = case_when(Gender == "male" ~ sum(Score),
TRUE ~ NA_real_))
For both 'Gender'
x %>%
group_by(Gender) %>%
mutate(totalScore = sum(Score))
Or in base R
x['totalScore'] <- with(x, sum(Score[Gender == "male"]))
Or to selectively add for the rows
i1 <- x$Gender == "male"
x['totalScore'][i1] <- sum(x$Score[i1])