0

I would like to sum rows of two columns based on a condition of a variable "country". The output should give a new column that has only values for specified countries and NA's for the rest. For instance:

P  R  Country Total
1  1  IT       2
2  2  DE       4
3  3  FR       NA
4  4  FR       NA
5  5  DE       10
6  6  IT       12
Laura
  • 306
  • 3
  • 12

1 Answers1

2

You can use ifelse for this:

your_data$Total = with(your_data, ifelse(Country %in% c("IT", "DE"), P + R, NA))
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294