如何检查列值是 R 中同一 tibble 的另一个 list-type 列的成员?
How to check column value is member of another list-type column of the same tibble in R?
tibble 包含一个列表作为列(这里是名为 Imgs
的列),我想检查另一列(这里是 Img
)中的值是否是该列的成员( Imgs
)。
我试过 mutate(In = ifelse(Img %in% Imgs[[1]], TRUE, FALSE))
,但他们都检查了 Imgs
的第一行。如您所见,Imgs
因 Condition
而异。
在基础 R 中,我们可以使用 mapply
/Map
df$In <- mapply(function(x, y) any(x %in% y), df$IMG, df$Imgs)
df
# Condition IMG Imgs In
#1 CHR 14 13, 19, 14 TRUE
#2 CHR 2 13, 19, 14 FALSE
#3 CHR 13 13, 19, 14 TRUE
或 map2_lgl
在 purrr
library(dplyr)
library(purrr)
df %>% mutate(In = map2_lgl(IMG,Imgs, ~any(.x %in% .y)))
测试此示例数据:
df <- data.frame(Condition = rep("CHR", 3), IMG = c(14, 2, 13))
df$Imgs <- list(c(13, 19, 14))
我们可以使用data.table
library(data.table)
setDT(df)[, In := unlist(Map(`%in%`, IMG, Imgs))][]
# Condition IMG Imgs In
#1: CHR 14 13,19,14 TRUE
#2: CHR 2 13,19,14 FALSE
#3: CHR 13 13,19,14 TRUE
tibble 包含一个列表作为列(这里是名为 Imgs
的列),我想检查另一列(这里是 Img
)中的值是否是该列的成员( Imgs
)。
我试过 mutate(In = ifelse(Img %in% Imgs[[1]], TRUE, FALSE))
,但他们都检查了 Imgs
的第一行。如您所见,Imgs
因 Condition
而异。
在基础 R 中,我们可以使用 mapply
/Map
df$In <- mapply(function(x, y) any(x %in% y), df$IMG, df$Imgs)
df
# Condition IMG Imgs In
#1 CHR 14 13, 19, 14 TRUE
#2 CHR 2 13, 19, 14 FALSE
#3 CHR 13 13, 19, 14 TRUE
或 map2_lgl
在 purrr
library(dplyr)
library(purrr)
df %>% mutate(In = map2_lgl(IMG,Imgs, ~any(.x %in% .y)))
测试此示例数据:
df <- data.frame(Condition = rep("CHR", 3), IMG = c(14, 2, 13))
df$Imgs <- list(c(13, 19, 14))
我们可以使用data.table
library(data.table)
setDT(df)[, In := unlist(Map(`%in%`, IMG, Imgs))][]
# Condition IMG Imgs In
#1: CHR 14 13,19,14 TRUE
#2: CHR 2 13,19,14 FALSE
#3: CHR 13 13,19,14 TRUE