r - how to create a new variable based on a condition -
data file name: toys
lets have following dataframe
id name 1 green ball 2 red ball 3 blue bat 4 green bat 5 blue ball 6 ball 7 bat
i add new variable "color" searching color in name.
id name color 1 green ball green 2 red ball red 3 blue bat blue 4 green bat green 5 blue ball blue 6 ball other 7 bat other
i have never used r , not sure how go doing this. tried no luck.
toys$color <- ( if toys$name = "green", color "green" else if toys$name = "red", color "red" else if toys$name = "blue, color "blue" else toys$name = "other" )
i appreciate assistance this.
thanks
we can use str_extract
. create vector
of colors ('col1'), use str_extract
substrings in 'name' match elements in 'col1' paste
ingthe 'col1' single string separated by
|. replace the
na` elements in output 'other' create new column 'color'.
library(stringr) col1 <- c("green", "red", "blue") v1 <- str_extract(toys$name, paste(col1, collapse="|")) v1[is.na(v1)] <- "other" toys$color <- v1 toys # id name color #1 1 green ball green #2 2 red ball red #3 3 blue bat blue #4 4 green bat green #5 5 blue ball blue #6 6 ball other #7 7 bat other
Comments
Post a Comment