Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating several dichotomous variables by changing the condition in a loop

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?

like image 935
Mircea_cel_Batran Avatar asked Dec 07 '25 05:12

Mircea_cel_Batran


1 Answers

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)
}
like image 199
slava-kohut Avatar answered Dec 08 '25 18:12

slava-kohut