gpt4 book ai didi

r - R中组中的ifelse函数组

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

我有数据集

ID <- c(1,1,2,2,2,2,3,3,3,3,3,4,4,4)
Eval <- c("A","A","B","B","A","A","A","A","B","B","A","A","A","B")
med <- c("c","d","k","k","h","h","c","d","h","h","h","c","h","k")
df <- data.frame(ID,Eval,med)
> df
ID Eval med
1 1 A c
2 1 A d
3 2 B k
4 2 B k
5 2 A h
6 2 A h
7 3 A c
8 3 A d
9 3 B h
10 3 B h
11 3 A h
12 4 A c
13 4 A h
14 4 B k

我尝试创建变量 xy , 按 ID 和 Eval 分组。对于每个 ID, if Eval = A, and med = "h" or "k" , 我设置 x = 1 , 否则 x = 0 , if Eval = B and med = "h" or "k" , 我设置 y = 1 , 否则 y = 0 .我用我不喜欢的方式,我得到了答案,但似乎不是那么好
df <- data.table(df)
setDT(df)[, count := uniqueN(med) , by = .(ID,Eval)]
setDT(df)[Eval == "A", x:= ifelse(count == 1 & med %in% c("k","h"),1,0), by=ID]
setDT(df)[Eval == "B", y:= ifelse(count == 1 & med %in% c("k","h"),1,0), by=ID]


ID Eval med count x y
1: 1 A c 2 0 NA
2: 1 A d 2 0 NA
3: 2 B k 1 NA 1
4: 2 B k 1 NA 1
5: 2 A h 1 1 NA
6: 2 A h 1 1 NA
7: 3 A c 3 0 NA
8: 3 A d 3 0 NA
9: 3 B h 1 NA 1
10: 3 B h 1 NA 1
11: 3 A h 3 0 NA
12: 4 A c 2 0 NA
13: 4 A h 2 0 NA
14: 4 B k 1 NA 1

然后我需要折叠行以获得唯一 ID,我不知道如何折叠行,知道吗?

输出
 ID x y
1 0 0
2 1 1
3 0 1
4 0 1

最佳答案

我们创建了按 'ID' 分组的 'x' 和 'y' 变量,而没有 NA 元素直接将逻辑向量强制转换为二进制 ( as.integer )

df[, x := as.integer(Eval == "A" & count ==1 & med %in% c("h", "k")) , by = ID]

和类似的“y”
df[, y := as.integer(Eval == "B" & count ==1 & med %in% c("h", "k")) , by = ID]

并总结它,使用 any按“ID”分组后
df[, lapply(.SD, function(x) as.integer(any(x))) , ID, .SDcols = x:y]
# ID x y
#1: 1 0 0
#2: 2 1 1
#3: 3 0 1
#4: 4 0 1

如果我们需要一个紧凑的方法,而不是分配( := ),我们根据条件汇总按“ID”、“Eval”分组的输出,然后按“ID”分组,我们检查是否有 any通过循环遍历 .SDcols 中描述的列,在 'x' 和 'y' 中获得 TRUE 值.
setDT(df)[,  if(any(uniqueN(med)==1 & med %in% c("h", "k"))) {
.(x= Eval=="A", y= Eval == "B") } else .(x=FALSE, y=FALSE),
by = .(ID, Eval)][, lapply(.SD, any) , by = ID, .SDcols = x:y]
# ID x y
#1: 1 FALSE FALSE
#2: 2 TRUE TRUE
#3: 3 FALSE TRUE
#4: 4 FALSE TRUE

如果需要,我们可以类似于第一个解决方案中显示的方法转换为二进制。

关于r - R中组中的ifelse函数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38419131/

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