最近在试图做一个产品路径的数据处理,逻辑是对同一个 id,'target' 字段取下一行的 ‘item’ 值,代码如下:
id <- c('1001','1001','1001','1002','1002','1003','1003','1003','1003')
item <- c('milk','bread','cake','milk','sugar','bread','cake','cafe','milk')
df1 <- data.frame(id, item, stringsAsFactors = F)
for (i in c(1:length(df1$id-1))
if(df1$id[i+1]==df1$id[i]df1$id)df1target[i] <- df1$item[i+1]
else(df1$item[i+1]else(df1target <- NA)
}
得到错误提示:argument is of length zero
希望得到:
id item target
1001 milk bread
1001 bread cake
1001 cake NA
1002 milk sugar
1002 sugar NA
1003 bread cake
1003 cake cafe
1003 cafe milk
1003 milk NA
解决方法:
用括号把 (length(df1id−1)括起来了变成1:(length(df1id)-1), 这样结果就得到 1 2 3 4 5 6 7 8,避免了从 0 开始的报错了💛
暂无数据