如果一个列表的内容在R中的另一个列表中,则写入新列

问题描述 投票:0回答:3

假设我有几个颜色列表,其中每个列表对应一个给定的人。我想创建一个主列表,所以我知道哪个人的列表中有哪些颜色。

这是示例数据:

Sarah <- c("Red", "Blue", "Yellow", "Green", "Pink")
Ben <- c("Black", "White", "Silver", "Pink", "Red", "Purple")
Jenny <- c("Green", "Orange", "Gold")

people <- list(Sarah, Ben, Jenny)
names(people) <- c("Sarah", "Ben", "Jenny")
allcolors <- c( Sarah, Ben, Jenny)

colorSet <- data.frame(colors = allcolors)

我想要一张主表,其中到达行对应一种颜色,每列对应一个人。如果此人的列表中有颜色,那么该单元格将为TRUE,如果他们的列表中没有颜色,那么它将为FALSE。

这是我尝试过的,但它没有奏效。

for (i in 1:length(people)) {

   sub_people <- people[[i]]
   sub_people_name <- names(people[i])
   colorSet$x <- ifelse(which(sub_people %in% colorSet$colors), TRUE, FALSE)
   names(colorSet)[names(colorSet) == x] <- sub_people_name

 }

这是我得到的错误:

$<-.data.frame错误(*tmp*,“x”,value = c(TRUE,TRUE,TRUE,TRUE,:替换有5行,数据有14行)

任何帮助将不胜感激!

r dataframe data.table
3个回答
2
投票

这适用于基数R:

colorSet$Sarah <- colorSet$colors %in% Sarah
colorSet$Ben <- colorSet$colors %in% Ben
colorSet$Jenny <- colorSet$colors %in% Jenny

colorSet返回的地方:

   colors Sarah   Ben Jenny
1     Red  TRUE  TRUE FALSE
2    Blue  TRUE FALSE FALSE
3  Yellow  TRUE FALSE FALSE
4   Green  TRUE FALSE  TRUE
5    Pink  TRUE  TRUE FALSE
6   Black FALSE  TRUE FALSE
7   White FALSE  TRUE FALSE
8  Silver FALSE  TRUE FALSE
9    Pink  TRUE  TRUE FALSE
10    Red  TRUE  TRUE FALSE
11 Purple FALSE  TRUE FALSE
12  Green  TRUE FALSE  TRUE
13 Orange FALSE FALSE  TRUE
14   Gold FALSE FALSE  TRUE

这应该也有效:

l <- rbind.data.frame(lapply(people, function(x) colorSet$colors %in% x))
l$colors <- colorSet$colors

有了purrr,我们可以做到:

purrr::map_df(people, function(x) colorSet$colors %in% x)

# Alternatively, if you prefer formula syntax
purrr::map_df(people, ~ colorSet$colors %in% .)

返回:

# A tibble: 14 x 3
   Sarah Ben   Jenny
   <lgl> <lgl> <lgl>
 1 TRUE  TRUE  FALSE
 2 TRUE  FALSE FALSE
 3 TRUE  FALSE FALSE
 4 TRUE  FALSE TRUE 
 5 TRUE  TRUE  FALSE
 6 FALSE TRUE  FALSE
 7 FALSE TRUE  FALSE
 8 FALSE TRUE  FALSE
 9 TRUE  TRUE  FALSE
10 TRUE  TRUE  FALSE
11 FALSE TRUE  FALSE
12 TRUE  FALSE TRUE 
13 FALSE FALSE TRUE 
14 FALSE FALSE TRUE

0
投票
Sarah <- c("Red", "Blue", "Yellow", "Green", "Pink")
Ben <- c("Black", "White", "Silver", "Pink", "Red", "Purple")
Jenny <- c("Green", "Orange", "Gold")

m_color <-unique(c(Sarah,Ben,Jenny))

TF <-data.frame(color = m_color)

TF$Sarah <- m_color%in%Sarah
TF$Ben <- m_color%in%Ben
TF$Jenny <- m_color%in%Jenny

0
投票

以下使用sapply。这样一来就不必重复人名。

all_colours <- unique(allcolors)
tab <- sapply(people, function(x) all_colours %in% x)
rownames(tab) <- all_colours

tab
#        Sarah   Ben Jenny
# Red     TRUE  TRUE FALSE
# Blue    TRUE FALSE FALSE
# Yellow  TRUE FALSE FALSE
# Green   TRUE FALSE  TRUE
# Pink    TRUE  TRUE FALSE
# Black  FALSE  TRUE FALSE
# White  FALSE  TRUE FALSE
# Silver FALSE  TRUE FALSE
# Purple FALSE  TRUE FALSE
# Orange FALSE FALSE  TRUE
# Gold   FALSE FALSE  TRUE
© www.soinside.com 2019 - 2024. All rights reserved.