【发布时间】:2016-11-16 10:07:41
【问题描述】:
我正在尝试解决 R 中的数据管理问题。
假设我的数据如下所示:
id <- c("123", "414", "606")
next.up <- c("414", "606", "119")
is.cond.met <- as.factor(c("FALSE", "FALSE", "TRUE"))
df <- data.frame(id, next.up, is.cond.met)
> df
id next.up is.cond.met
1 123 414 FALSE
2 414 606 FALSE
3 606 119 TRUE
我想获得的是以下内容:
id <- c("123", "414", "606")
next.up <- c("414", "606", "119")
is.cond.met <- as.factor(c("FALSE", "FALSE", "TRUE"))
origin <- c("606", "606", "119")
df.result <- data.frame(id, next.up, is.cond.met, origin)
> df.result
id next.up is.cond.met origin
1 123 414 FALSE 606
2 414 606 FALSE 606
3 606 119 TRUE 119
换句话说:当给定条件(is.met)为真时,我想将每个 ID 与其“原点”匹配。我遇到的困难是这是迭代和分层的:要找到原点,我可能必须经历多层次的分离。逻辑步骤如下所示。我真的不知道如何在 R 中解决这个问题。
更新
其中一个 cmets 提出了一种适用于已排序数据的 data.frame 解决方案,如上面的最小示例所示。事实上,我的数据并没有以这种方式排序。一个更好的例子如下:
id <- c("961980", "14788", "902460", "900748", "728912", "141726", "1041190", "692268")
next.up <- c("20090", "655036", "40375164", "40031850", "40368996", "961980", "141726", "760112")
is.cond.met <- c(TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE)
df <- data.frame(id, next.up, is.cond.met, stringsAsFactors = FALSE)
glimpse(df)
Observations: 8
Variables: 3
$ id <chr> "961980", "14788", "902460", "900748", "728912", "141726", "1041190", "692268"
$ next.up <chr> "20090", "655036", "40375164", "40031850", "40368996", "961980", "141726", "760112"
$ is.cond.met <lgl> TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE
> df
id next.up is.cond.met
1 961980 20090 TRUE
2 14788 655036 FALSE
3 902460 40375164 FALSE
4 900748 40031850 FALSE
5 728912 40368996 FALSE
6 141726 961980 FALSE
7 1041190 141726 FALSE
8 692268 760112 FALSE
更新 2:最终结果应如下所示:
> df.end.result
id next.up is.cond.met origin
1 961980 20090 TRUE <NA>
2 14788 655036 FALSE <NA>
3 902460 40375164 FALSE <NA>
4 900748 40031850 FALSE <NA>
5 728912 40368996 FALSE <NA>
6 141726 961980 FALSE 961980
7 1041190 141726 FALSE 961980
8 692268 760112 FALSE <NA>
【问题讨论】:
-
您可以在示例中再添加几行吗?我不确定我是否遵循逻辑
-
您是否尝试匹配来自 2 个不同数据集的条目?这是我能尝试理解的唯一意义。如果是这种情况,明确说明可能会有所帮助。
-
@BryanGoggin 不,数据与 df 中的一样。 df.result 只显示我希望最终结果的样子。
-
如果您在更新示例中提到的数据存在差距,结果应该是什么?算法应该只在下一行还是在所有后续行中搜索 next.up?如果找不到 next.up,算法应该怎么做?
-
@George91 它应该搜索所有以下(和/或以前)行。如果未找到匹配项,则 origin==NA
标签: r loops dplyr data-manipulation tidyr