【发布时间】:2017-12-14 14:21:07
【问题描述】:
对于myvector1 的每个值,我想知道myvector1 中前一个相同值的mycategory 值,因为mystatus 是ON,否则我会看对应下一个相同的值,直到它为 ON。
说明如下:
- 对于“myvector”的给定位置,给我他的值。
- 在中查找中间前一个相同值的位置 “我的向量”
- 检查关联状态。如果它是 ON 给我他的关联 “我的类别”。如果它是关闭的,重复到第 2 点。
- 将获得的“mycategory”分配给新的向量“mysolution”。
给定数据集mydf,我要查找的是DesiredSolution(我手动填写的)。
mydf <- structure(list(myvector1 = structure(c(1L, 2L, 3L, 4L, 5L, 1L,
2L, 4L, 5L, 2L, 3L, 4L, 5L, 2L, 3L, 5L, 1L, 2L, 3L, 4L, 5L, 1L,
2L, 4L, 5L, 1L, 1L, 2L, 3L, 4L, 5L, 3L), .Label = c("0", "1",
"2", "3", "4"), class = "factor"), mystatus = structure(c(2L,
1L, 2L, 2L, 1L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 2L, 2L, 2L,
1L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 2L), .Label = c("OFF",
"ON"), class = "factor"), mycategory = structure(c(2L, 2L, 3L,
1L, 1L, 1L, 1L, 3L, 3L, 1L, 2L, 2L, 3L, 1L, 1L, 1L, 1L, 1L, 2L,
2L, 3L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L), .Label = c("bye",
"hi", "stay"), class = "factor"), DesiredSolution = structure(c(3L,
3L, 3L, 3L, 3L, 2L, 3L, 1L, 3L, 1L, 4L, 4L, 4L, 1L, 2L, 4L, 1L,
1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 2L), .Label = c("bye",
"hi", "NA", "stay"), class = "factor")), .Names = c("myvector1",
"mystatus", "mycategory", "DesiredSolution"), row.names = c(NA,
-32L), class = "data.frame")
【问题讨论】: