lundi 31 juillet 2017

Create new column within a loop based on ifelse statement in R.

I am not getting the expected results when I attempt to create a new column based upon an ifelse statement placed within a loop. The data in the new column is only based on some of the columns that are in the loop and not all of them. Why is this and how can I make the data in the new column be based on all the information in the loop? Here is a reproducible example of my attempt, in reality my dataframe contains over 500 columns:

 x1 <- sample( LETTERS[1:4], 100, replace=TRUE, prob=c(0.1, 0.2, 0.65, 0.05) )
 x2 <- sample( LETTERS[1:4], 100, replace=TRUE, prob=c(0.1, 0.2, 0.65, 0.05) )
 x3 <- sample( LETTERS[1:4], 100, replace=TRUE, prob=c(0.1, 0.2, 0.65, 0.05) )
 x4 <- sample( LETTERS[1:4], 100, replace=TRUE, prob=c(0.1, 0.2, 0.65, 0.05) )
 x5 <- sample( LETTERS[1:4], 100, replace=TRUE, prob=c(0.1, 0.2, 0.65, 0.05) )
 x6 <- sample( LETTERS[1:4], 100, replace=TRUE, prob=c(0.1, 0.2, 0.65, 0.05) )
 x7 <- sample( LETTERS[1:4], 100, replace=TRUE, prob=c(0.1, 0.2, 0.65, 0.05) )
 x8 <- sample( LETTERS[1:4], 100, replace=TRUE, prob=c(0.1, 0.2, 0.65, 0.05) )
 df <- data.frame(x1,x2,x3,x4, x5,x6,x7,x8,stringsAsFactors=FALSE)

 for (i in 2:7){
   df$newvar <- ifelse(df[,i] == "B" ,1,0)
 }

Aucun commentaire:

Enregistrer un commentaire