让我说我有一个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"))
我如何制作它以便我可以在填充新列的行上使用if else语句,如果满足特定条件,它会取消(i + 1)和(i)行之间的差异?例如:
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
}
}
这不起作用..新列应该有行1,5,6,7,8 = 0,行2,3,4等于第3列中的差异(iw第2行新column =第3行第2列 - 第2行第2列之间的差异
答案 0 :(得分:0)
我不知道你想对最后一个元素做什么,所以我只是保持原样
#set up our i and i+1 vectors for the column def
ithDef<-data111$def[1:(nrow(data111)-1)]
i_plus_1Def<-data111$def[2:(nrow(data111))]
##set up our i and i+1 vectors for the column ghi
ithGhi<-data111$ghi[1:(nrow(data111)-1)]
i_plus_1Ghi<-data111$ghi[2:(nrow(data111))]
#the last element has no i+1, so I keep the last element the same
newNew<-c(ifelse(ithDef==i_plus_1Def, i_plus_1Ghi-ithGhi, 0), df$new[nrow(df)])