Add new variable with for loop and if statements in R -
let's assume have data set 2 variables, , b, b's a's, not a's b's.
a<-rbind(1,1,1,1,1) b<-rbind(0,0,0,1,1) d<-cbind(a,b) d [,1] [,2] [1,] 1 0 [2,] 1 0 [3,] 1 0 [4,] 1 1 [5,] 1 1
i want create new third variable condense information single data frame. attempted writing loop 1 in nrows, if variable 1 write 2, , if b variable 1 write 1
e<- (i in 1:nrow(d)) { if (d[,1]==1) { e$new[,i] <- 2 } # end if 1 else (d[,2]==1) e$new[,i]<-1 } # end 2 } # end
i want output such:
> d [,1] [,2] [,3] [1,] 1 0 2 [2,] 1 0 2 [3,] 1 0 2 [4,] 1 1 1 [5,] 1 1 1
i keep getting error: error in e$new[, i] <- 0 : incorrect number of subscripts on matrix in addition: warning messages: 1: in 1:x : numerical expression has 2 elements: first used 2: in if (d[, 1] == 1) { : condition has length > 1 , first element used
any debugging script appreciated!
to make things easier, converted matrix data frame
a<-rbind(1,1,1,1,1) b<-rbind(0,0,0,1,1) d<-as.data.frame(cbind(a,b))
this makes operations easier (if necessary, can use as.matrix(data_frame) convert matrix)
here loop came with
for(i in 1:nrow(d)){ if((d[i,1] == 1 & d[i,2] == 0) == true){ d$v3[i] <- 2 }else if((d[i,2] == 1) == true){ d$v3[i] <- 1 } }
what believe happening want test condition 1 element equal one, operation returns vector. therefore, altered condition adding row , column subscript , making boolean.
another possibility achieve result expecting use ifelse command in following way
##this recreate data frame remove(list = ls()) a<-rbind(1,1,1,1,1) b<-rbind(0,0,0,1,1) d<-as.data.frame(cbind(a,b)) d$v3 <- ifelse(d$v1 == 1 & d$v2 == 0, 2,1)
Comments
Post a Comment