Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding a column, of which the values depend on whether the value in another column, matches one of four vectors

I have data as follows:

library(stringi)

datfake <- as.data.frame(runif(100, 0, 3000))
names(datfake)[1] <- "Inc"
datfake$type <- sample(LETTERS, 100, replace = TRUE)
datfake$province <- stri_rand_strings(100, 1, "[A-P]")

region_south <- c("A", "B", "C", "D")
region_north <- c("E", "F", "G", "H", "I")
region_east <- c("J", "K", "L")
region_west <- c("M", "N", "O", "P")

I would like to add a column that tells me in which reason each province is. All the solutions I come up with are a bit clunky (for example turning the vector region_south into a two column dataframe, where the second column says south and then merging). What would be the easiest way to do this?

Desired output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

        Inc      type province region
1  297.7387         C        J   east
2 2429.0961         E        D  south

>Solution :

An idea is to use mget to get the regions, unlist and take advantage of the named vector object and match the values with province and return the names, i.e.

v1 <- unlist(mget(ls(.GlobalEnv, pattern = 'region_')))
res <- names(v1)[match(datfake$province, v1)]
gsub('region_(.+)[0-9]+','\\1' ,res)


  [1] "north" "east"  "north" "north" "south" "south" "south" "west"  "west"  "east"  "south" "south" "west"  "north" "north" "south" "east"  "north" "south" "east"  "north" "west" 
 [23] "south" "west"  "north" "west"  "east"  "north" "east"  "south" "south" "east"  "south" "west"  "north" "east"  "west"  "south" "south" "east"  "north" "west"  "west"  "south"
 [45] "north" "east"  "south" "west"  "north" "south" "east"  "west"  "north" "north" "north" "south" "north" "south" "north" "north" "west"  "north" "north" "south" "west"  "north"
 [67] "east"  "south" "north" "west"  "south" "west"  "north" "north" "north" "south" "north" "east"  "west"  "south" "west"  "north" "west"  "east"  "north" "west"  "south" "east" 
 [89] "north" "west"  "north" "north" "west"  "south" "west"  "north" "west"  "west"  "south" "west"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading