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' pasteingthe 'col1' single string separated by|. replace thena` 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

Popular posts from this blog

sequelize.js - Sequelize group by with association includes id -

android - Robolectric "INTERNET permission is required" -

java - Android raising EPERM (Operation not permitted) when attempting to send UDP packet after network connection -