[英]Check if value is in array of values in r dataframe
我有一个包含两列Fruits
和Groups
的数据框。 我想检查Fruits
的值是否为Groups
的数组。 如果是,则改变新字段并添加是或否。
df <- data.frame(Fruits = c("Apple","Banana","Orange","Kiwi"),
Group = I(list(c("Apple","Strawberry"),
c("Orange","Kiwi"),
c("Apple","Banana"),
c("Apple","Kiwi")
)))
df$Fruits %in% df$Group
由于Group
是一个列表,我们无法直接比较它。 一种方法是使用mapply
df$Present <- c("No", "Yes")[mapply(`%in%`, df$Fruits, df$Group) + 1]
df
# Fruits Group Present
#1 Apple Apple, S.... Yes
#2 Banana Orange, Kiwi No
#3 Orange Apple, B.... No
#4 Kiwi Apple, Kiwi Yes
mapply
返回TRUE
/ FALSE
值,然后我们使用索引技术得到Yes
/ No
。
mapply(`%in%`, df$Fruits, df$Group)
#[1] TRUE FALSE FALSE TRUE
或者类似于purrr
map2_lgl
library(dplyr)
library(purrr)
df %>%
mutate(Present = c("No", "Yes")[map2_lgl(Fruits, Group, `%in%`) + 1])
我们可以用
library(data.table)
setDT(df)[, Present := unlist(Map(`%in%`, Fruits, Group))]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.