Apologies if this is a simple problem, I was really struggling to find a solution. There's this question here which is similar, but not quite the same and none of the solutions seemed to work for me: Replacing row elements in a column based on row elements from another column in Tidyverse
I have a df as follows:
Loop <- c('0','1','','0','1','2','0','1','','0','1','2')
Condition <- c('base','base','base','AOMI1','AOMI1','AOMI1','control','control',
'control','AOMI2','AOMI2','AOMI2')
df <- data.frame(Loop, Condition)
Loop Condition
1 0 base
2 1 base
3 base
4 0 AOMI1
5 1 AOMI1
6 2 AOMI1
7 0 control
8 1 control
9 control
10 0 AOMI2
11 1 AOMI2
12 2 AOMI2
I want to rename all instances of '1' in the column called 'Loop' but differently for different conditions in the 'Condition' column. For the 'base' and 'control' conditions I want '1' to be renamed 'imageryQ' and for 'AOMI1' and 'AOMI2' I want '1' to become 'VI'. This is what I want the data to look like:
Loop2 Condition
1 0 base
2 imageryQ base
3 base
4 0 AOMI1
5 VI AOMI1
6 2 AOMI1
7 0 control
8 imageryQ control
9 control
10 0 AOMI2
11 VI AOMI2
12 2 AOMI2
It would be better if this could be done based on the column contents as opposed to row numbers as I'm not sure whether the data could change. It's unlikely to change though, so if a solution using row numbers is much simpler those options would be good too!
Any help much appreciated.
CodePudding user response:
This can be done using a simple dplyr::case_when function:
library(tidyverse)
Loop <- c('0','1','','0','1','2','0','1','','0','1','2')
Condition <- c('base','base','base','AOMI1','AOMI1','AOMI1','control','control',
'control','AOMI2','AOMI2','AOMI2')
df <- data.frame(Loop, Condition)
df %>%
mutate(Loop = case_when(
Loop == "1" & Condition == "base" ~ "imageryQ",
Loop == "1" & Condition == "control" ~ "imageryQ",
Loop == "1" & Condition == "AOMI1" ~ "VI",
Loop == "1" & Condition == "AOMI2" ~ "VI",
TRUE ~ Loop
))
You can shorten this up by writing
Loop == "1" & Condition %in% c("base","contorl") ~ "imageryQ"