gpt4 book ai didi

r - 更新 id 到它的 parent_id 除非它有不同的值

转载 作者:行者123 更新时间:2023-12-04 12:12:37 24 4
gpt4 key购买 nike

首先对问题标题不明确表示歉意,这是一个非常具体的问题,我不知道如何用一行来表达!

无论如何,我的问题如下。我有一个数据框,其中包含一个 ID、一个父 ID 和两个值,比如 a 和 b。我想将一行的 id 更新为它的 parent_id,除非它的值不等于它的 parent_id。

例如,假设我有一张 table :

id parent_id a b  
1 0 x x
2 1 x x
3 1 x y
4 0 y y
5 4 x x
6 1 x x
7 4 y y

可以用代码生成

 x <- data.frame('id' = c(1,2,3,4,5,6,7),
'parent_id' = c(0,1,1,0,4,1,4),
'a' = c('x','x','x','y','x','x','y'),
'b' = c('x','x','y','y','x','x','y'))

这应该变成:

id parent_id a b
1 0 x x
1 1 x x
3 1 x y
4 0 y y
5 4 x x
1 1 x x
4 4 y y

所以 id 2 变成了 1,因为那是它的 parent_id,而且属性 ab 是两者都等于 x,与 id 1 相同,但是 id 3 保持不变,尽管它的 parent_id1,它没有相同的属性。

如有任何帮助,我们将不胜感激。

最佳答案

其他人可能有更优雅的解决方案,但这可以满足您的需求:

# list of a-b pairs for parent_id
parent.id.ab <- with(x, lapply(parent_id, FUN=function(y) c(a[id==y], b[id==y])))

# list of a-b pairs for id
id.ab <- with(x, mapply(function(y,z) c(y,z), a, b, SIMPLIFY=FALSE))

# condition is a vector of TRUE/FALSE, TRUE if the parent_id a-b pair equals the id a-b.
# When the parent_id is 0, its a-b pair is integer(0). Since all(logical(0)) is TRUE,
# we only use all(z == y) when z and y have the same length.
condition <- mapply(function(z,y) if (length(z) == length(y)) all(z == y) else FALSE,
parent.id.ab, id.ab)

x$id <- ifelse(condition, x$parent_id, x$id)

关于r - 更新 id 到它的 parent_id 除非它有不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11126301/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com