if statement - How to change a value in a column dependent on a grepl in R -
i change values in 1 column depending on match in grepl column in data.frame.
example of data.frame:
df shot class data_text shot1 missed missed jumper shot2 made made 3 point jumper shot3 made made jumper
what have been trying:
df$shot_type <- as.vector(0) #create new variable (i in 1:length(df)) { if(grepl("e jumper", df$data_text[i])) { df$shot_type <- "jumper" } else if(grepl("d jumper", df$data_text[i])) { df$shot_type <- "jumper" } else if(grepl("t jumper", df$data_text[i])) { df$shot_type <- "three" } }
doing method each if statement
overwrites last.
my current results:
df shot class data_text shot_type shot1 missed missed jumper 3 shot2 made made 3 point jumper 3 shot3 made made jumper 3
what results like:
df shot class data_text shot_type shot1 missed missed jumper jumper shot2 made made 3 point jumper jumper shot3 made made jumper 3
any appreciated. please let me know if further information needed.
how this:
df$shot_type <- ifelse(grepl('d jumper|t jumper', df$data_text), 'jumper', ifelse(grepl('e jumper', df$data_text), 'three', na))
produces output:
shot class data_text shot_type 1 shot1 missed missed jumper jumper 2 shot2 made made 3 point jumper jumper 3 shot3 made made jumper 3
note: coded na columns don't match 3 patterns. can modify code suit need.
Comments
Post a Comment