r - How to code a for-loop over a dataframe using if else statements to create a few new variables -
i have troubles during for-loop. furthermore think way code inefficient.
i have data.frame (df) consists of binary-coded data follows (this subset, have fifty columns in total):
product1 product2 product3 product4 0 1 1 1 0 0 0 1 1 0 1 1 i want create new variable when combinations of products matches "1"
i using for loop. code shows 1 example of classification.
for (x in 1:dim(df)){ if (product1==1 | product2==1 | product4==1) { df$newclass <- 1 } else { df$newclass <- 0 } } how can make work?
do want create new column ifelse? if so, can write without for loop.
product$newclass <- ifelse(product1==1 | product2==1 | product3==1 | product4==1, 1, 0) > product product1 product2 product3 product4 newclass 1 0 1 1 1 1 2 0 0 0 1 1 3 1 0 1 1 1
Comments
Post a Comment