Monday, 15 June 2015

r - using if else statements over multiple rows -



r - using if else statements over multiple rows -

lets have df

data111 <- structure(list(`1` = c(20.47039, 21.94899, 22.96345, 23.61655, 24.50835, 25.92349, 26.34687, 27.83433), `2` = structure(c(4l, 5l, 2l, 5l, 2l, 3l, 1l, 6l), .label = c("no", "p", "xa", "xae", "xei", "xoe"), class = "factor"), `3` = c(20.65273, 22.0617, 23.06622, 23.68949, 24.57134, 26.01042, 26.44185, 27.93414)), .names = c("1", "2", "3"), class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6", "7", "8"))

how create can utilize if else statement on rows new column populated , takes difference between (i+1) , (i) row if specific status met? example:

for (i in 1:nrow(data111)) { if (data111$def[i] == data111$def[i+1]) { data111$new <- data111$ghi[i+1] - data111$ghi[i] } else { data111$new <- 0 } }

this isn't working.. new columns should have rows 1,5,6,7,8 = 0, , rows 2,3,4 equal difference in 3rd column (i.w. row 2 new column = difference between row 3 column 2 - row 2 column 2)

i don't know want lastly element, kept is

#set our , i+1 vectors column def ithdef<-data111$def[1:(nrow(data111)-1)] i_plus_1def<-data111$def[2:(nrow(data111))] ##set our , i+1 vectors column ghi ithghi<-data111$ghi[1:(nrow(data111)-1)] i_plus_1ghi<-data111$ghi[2:(nrow(data111))] #the lastly element has no i+1, maintain lastly element same newnew<-c(ifelse(ithdef==i_plus_1def, i_plus_1ghi-ithghi, 0), df$new[nrow(df)])

r if-statement row

No comments:

Post a Comment