I am trying to write R code that
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())) ))
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))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With