假设我有几个颜色列表,其中每个列表对应一个给定的人。我想创建一个主列表,所以我知道哪个人的列表中有哪些颜色。
以下是示例数据:
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*
,&#34; x&#34;,值= c(TRUE,TRUE,TRUE,TRUE,:
替换有5行,数据有14行
非常感谢任何帮助!
答案 0 :(得分: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
答案 1 :(得分:0)
$
答案 2 :(得分: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