0

I have two columns - "end_use_type", and "tonnes". I'm trying to make a third column, with the values from "tonnes" but only for rows with an "end_use_type" of "Discards". New column would be named "tonnes_discards".

I think I want to use the mutate function, but can not figure out how to actually select for just the values for Discards.

This is what I have so far, which is not much and may not even be right.

  select(c(end_use_type, tonnes)) %>% 
  mutate()
mcmahsta
  • 1
  • 2
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Dec 13 '20 at 03:19

1 Answers1

1

You probably want case_when.

try:

select(end_use_type, tonnes) %>%
    mutate(tonnes_discards = case_when(end_use_type == 'Discards' ~ tonnes, TRUE ~ NA_Character)

The code is copying the values tonnes column into the new tonnes_discards column when the end_use_type is equal to 'Discards' (mind the capitalisation). When it is not equal to 'Discards', it inserts an NA. You can replace that NA_Character with whatever you want (maybe zero?).

Have a look at the dplyr case_when help files if you get stuck but you should be ok with this.

Dom
  • 1,043
  • 2
  • 10
  • 20