gpt4 book ai didi

r - 根据条件匹配R中多列中的值

转载 作者:行者123 更新时间:2023-12-05 08:26:13 26 4
gpt4 key购买 nike

假设我有一个数据名 df

resident    faculty    submittedBy    match    caseID    phase

george sally george 1 george_1 pre
george sally sally 0 george_1 pre
george sally george 1 george_1 intra
jane carl jane 1 jane_1 pre
jane carl carl 0 jane_1 pre
jane carl carl 0 jane_1 intra

我想根据以下参数向此数据框添加一列 df$response(我想我需要一组嵌套的 ifelses,但我正在努力正确执行它):

对于给定的行 X,如果 df$match = 1,

df$response 中打印“1”,如果:

df$match

any row 其中 df$match = 0 在 中具有相同的内容>df$caseIDdf$facultydf$phase 作为第 X 行。否则打印“0”。

所以输出应该是这样的:

response

1
0
0
1
0
0

因为只有第一行和第四行包含在 df$caseIDdf$facultydf$phase 中匹配的值> 对于 df$match = 1 的行和 df$match = 0 的行。

最佳答案

我们可以使用data.table 方法。将'data.frame'转换为'data.table'(setDT(df1)),按'caseID'、'faculty'、'phase'分组,得到unique<的长度 match 的元素检查它是否等于 2 并创建一个二进制列('response'),对于 'match' 为 0' 的值,将 'response' 分配给 0

library(data.table)
setDT(df1)[, response := +((uniqueN(match) == 2) & match != 0),
.(caseID, faculty, phase)][]
# resident faculty submittedBy match caseID phase response
#1: george sally george 1 george_1 pre 1
#2: george sally sally 0 george_1 pre 0
#3: george sally george 1 george_1 intra 0
#4: jane carl jane 1 jane_1 pre 1
#5: jane carl carl 0 jane_1 pre 0
#6: jane carl carl 0 jane_1 intra 0

或者使用 base Rave

with(df1,+( match != 0 & ave(match, caseID, faculty, phase, 
FUN = function(x) length(unique(x))) == 2))
#[1] 1 0 0 1 0 0

数据

df1 <- structure(list(resident = structure(c(1L, 1L, 1L, 2L, 2L, 2L), 
.Label = c("george",
"jane"), class = "factor"), faculty = structure(c(2L, 2L, 2L,
1L, 1L, 1L), .Label = c("carl", "sally"), class = "factor"),
submittedBy = structure(c(2L, 4L, 2L, 3L, 1L, 1L), .Label = c("carl",
"george", "jane", "sally"), class = "factor"), match = c(1L,
0L, 1L, 1L, 0L, 0L), caseID = structure(c(1L, 1L, 1L, 2L,
2L, 2L), .Label = c("george_1", "jane_1"), class = "factor"),
phase = structure(c(2L, 2L, 1L, 2L, 2L, 1L), .Label = c("intra",
"pre"), class = "factor")), class = "data.frame", row.names = c(NA,
-6L))

关于r - 根据条件匹配R中多列中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56944046/

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