I want to create several variables, 0/1, that meet a condition with a varying cutoff point. Using an interval of 50 to 100, I'd like to create a 0/1 variable for every point in between those two numbers, where 0 is less than and everything else is 1.
For example:
data1$V1<-ifelse(data1$Value<50, 0, 1)
where data1$Value has the information for the interval and data1$V1 is the first binary vector using 50 as a cutoff, but then data1$V2 would be 51, and so forth.
Some reproducible code as a starter:
data1<-data.frame(Value=sample(1:120, 50, replace=TRUE))
data1$V1<-ifelse(data1$Value<50, 0, 1)
data1$V2<-ifelse(data1$Value<51, 0, 1)
data1$V3<-ifelse(data1$Value<52, 0, 1)
How can I do this with a loop?
Perhaps, this will work you:
data1<-data.frame(Value=sample(1:120, 50, replace=TRUE))
r <- 1:50
vars <- paste0('V', r)
const <- 50
for (i in seq_along(vars)){
data1[[vars[i]]] <- ifelse(data1$Value<const+i-1, 0, 1)
}
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