Geogrammer
Geogrammer

Reputation: 137

Dynamically creating columns of binary values based on a series True/False conditions

I would like to be able to create new columns in a dataframe, the values of which will be determined by a pre-defined list of conditional statements. The ultimate goal of this is to arrive at a table binary values that represent if a condition is being met for each instance. It may seem like a clunky or odd output, but it is the requirement of an economic model I'm trying to build (repeated sales model).

Here is a much simplified reproducible example:

df <- data.frame(a=c(1,2,3,4,5),b=c(0.3,0.2,0.5,0.3,0.7)) 
conditions <-   data.frame(y=df$b>=0.5, z=df$b>=0.7) 
columns <- c("y","z") 
for(i in length(columns)){ 
   df[, paste("var_",columns[i],sep="")] <- ifelse(conditions[i],1,0) 
} 

So in this instance, I'd like to get columns "var_y" and "var_z" which have binary values representing if the criteria for conditions y or z are being met.

Right now, I'm getting this error:

Error in ifelse(conditions[i], 1, 0) : (list) object cannot be coerced to type 'logical'

Which I don't understand, as all of the information in the dataframe "conditions" is of the type 'logical'.

Upvotes: 1

Views: 44

Answers (1)

akrun
akrun

Reputation: 887058

We can just do

df[paste0("var_", seq_along(columns))] <- +(conditions)
df
#  a   b var_1 var_2
#1 1 0.3     0     0
#2 2 0.2     0     0
#3 3 0.5     1     0
#4 4 0.3     0     0
#5 5 0.7     1     1

Upvotes: 1

Related Questions