如何根据R中任何给定列中是否存在值来返回真/假值?

如何根据R中任何给定列中是否存在值来返回真/假值?,r,R,我有一个看起来像这样的数据框: Fruits1 Fruits2 Fruits3 Apple Banana Lemon N/A N/A Apple N/A N/A N/A Apple Lemon N/A N/A N/A N/A N/A Banana Apple N/A

我有一个看起来像这样的数据框:

Fruits1     Fruits2   Fruits3       Apple      Banana       Lemon
N/A         N/A       Apple         N/A        N/A          N/A
Apple       Lemon     N/A           N/A        N/A          N/A
N/A         Banana    Apple         N/A        N/A          N/A
Fruits1     Fruits2   Fruits3      Apple       Banana       Lemon
N/A         N/A       Apple        TRUE        FALSE        FALSE
Apple       Lemon     N/A          TRUE        FALSE        TRUE
N/A         Banana    Apple        TRUE        TRUE         FALSE
我希望搜索前三列,然后在前三列的任何一行中出现该列名时,使用后三列名称返回真/假值,如下所示:

Fruits1     Fruits2   Fruits3       Apple      Banana       Lemon
N/A         N/A       Apple         N/A        N/A          N/A
Apple       Lemon     N/A           N/A        N/A          N/A
N/A         Banana    Apple         N/A        N/A          N/A
Fruits1     Fruits2   Fruits3      Apple       Banana       Lemon
N/A         N/A       Apple        TRUE        FALSE        FALSE
Apple       Lemon     N/A          TRUE        FALSE        TRUE
N/A         Banana    Apple        TRUE        TRUE         FALSE

base R
中,我们可以
unlist
前3列,使用
rep
应用行索引创建一个
,检查计数是否大于0,并将其分配回第4到第6列

df1[4:6] <- table(seq_len(nrow(df1))[row(df1[1:3])], unlist(df1[1:3]))[,1:3] > 0
df1
#  Fruits1 Fruits2 Fruits3 Apple Banana Lemon
#1     N/A     N/A   Apple  TRUE  FALSE FALSE
#2   Apple   Lemon     N/A  TRUE  FALSE  TRUE
#3     N/A  Banana   Apple  TRUE   TRUE FALSE

使用tidyverse时使用
聚集
分散

require(tidyverse)

df <- df %>% 
  select(Fruits1:Fruits3)

df %>% 
  mutate(i = row_number()) %>% 
  gather("key", "fruit", -i) %>% 
  filter(fruit != "N/A") %>% 
  select(-key) %>% 
  mutate(true = T) %>% 
  spread("fruit", "true", fill = F) %>% 
  select(-i) %>% 
  bind_cols(df, .)
require(tidyverse)
df%
选择(结果1:结果3)
df%>%
变异(i=行数())%>%
聚集(“键”、“水果”、-i)%>%
过滤器(水果!=“不适用”)%>%
选择(-key)%%>%
突变(真=T)%>%
摊铺(“水果”,“真实”,填充=F)%>%
选择(-i)%>%
绑定cols(df,.)

即使您在
base
r中添加了更多的水果,此解决方案仍然有效,您可以使用
apply
is.element
t
,如下所示:

df1[4:6] <- t(apply(df1[1:3], 1, is.element, el = names(df1[4:6])))

#   Fruits1 Fruits2 Fruits3 Apple Banana Lemon
# 1     N/A     N/A   Apple  TRUE  FALSE FALSE
# 2   Apple   Lemon     N/A  TRUE  FALSE  TRUE
# 3     N/A  Banana   Apple  TRUE   TRUE FALSE
df1[4:6]也
df1[4:6]