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

R create new variable if other variable contains vector

I want a create a treatment variable that takes the value of 1 for treated countries and 0 otherwise. I know how to do this individually for each country with transform but I was wondering if I can also add a vector to make it faster? I tired the following but I got an error (Warning: longer object length is not a multiple of shorter object length)

countries_vector <- c("USA", "UK", "ESP", "FR", "ITA")

df <- transform(df, treated = ifelse(Country == countries_vector, 1, 0))

>Solution :

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

You can use mutate, ifelse, and %in% to quickly assign 0 or 1.

library(dplyr)
treated_countries <- c("USA", "UK", "ESP", "FR", "ITA")
all_countries <- sample(x = c("USA", "UK", "ESP", "FR", "ITA", "BRA", "JAP", "CHN", "ZAF", "DEU"),
                  size = 100, replace = TRUE)
df <- as.data.frame(all_countries)
df <- df %>%
  mutate(treated = ifelse(all_countries %in% treated_countries, 1, 0))

df %>%
  group_by(treated, all_countries) %>%
  summarize()
#> `summarise()` has grouped output by 'treated'. You can override using the
#> `.groups` argument.
#> # A tibble: 10 × 2
#> # Groups:   treated [2]
#>    treated all_countries
#>      <dbl> <chr>        
#>  1       0 BRA          
#>  2       0 CHN          
#>  3       0 DEU          
#>  4       0 JAP          
#>  5       0 ZAF          
#>  6       1 ESP          
#>  7       1 FR           
#>  8       1 ITA          
#>  9       1 UK           
#> 10       1 USA
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