Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a new variable using IF, THEN, & Random value creation

Tags:

r

I am trying to write R code that

  1. creates a new variable
  2. populates that variable only if METRO=0
  3. the values that are populated are a random assignment of "1" and "2" values.

I tried something like this but it did not work:

iPUMS_2016 <- mutate (iPUMS_2016, metrounk = ifelse(METRO==0,mutate(rand_int=sample.int(n())) ))
like image 477
Quantitative72 Avatar asked Dec 04 '25 15:12

Quantitative72


1 Answers

We don't need the second mutate inside the ifelse. Also, it could be a if/else condition i.e. if all the elements in 'METRO' are 0 then get the sample.int on the number of rows

library(dplyr)
mutate(iPUMS_2016, metrounk = if(all(METRO == 0)) sample.int(n()) else  METRO)

If it is to replace only elements that are 0.

mutate(iPUMS_2016, metrounk = ifelse(METRO == 0, sample.int(n()), METRO))

The sample.int(n()) is not clear. Or it should be sample.int(sum(METRO == 0))

mutate(iPUMS_2016, metrounk = replace(METRO, METRO == 0, 
               sample.int(sum(METRO == 0, na.rm = TRUE))))
like image 104
akrun Avatar answered Dec 07 '25 04:12

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!