0

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?

zx8754
  • 52,746
  • 12
  • 114
  • 209
1.618
  • 227
  • 1
  • 2
  • 9
  • What's the output you want, just the sum of male values? – camille Dec 06 '19 at 03:45
  • @camille Yes. Using the specified source, I need to just calculate the sum of male scores. – 1.618 Dec 06 '19 at 03:47
  • So just filter/subset your data for just males, then sum score, unless there's something more complicated? Which is why seeing the output you want would be helpful – camille Dec 06 '19 at 03:52
  • @camille the question I guess would be how to filter that subset. – 1.618 Dec 06 '19 at 03:59

1 Answers1

2

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])
akrun
  • 874,273
  • 37
  • 540
  • 662