答案 0 :(得分:1)
使用dplyr
,您可group_by
colour
并查看是否只有一个unique
Pack
:
library(dplyr)
res <- df %>% group_by(colour) %>% mutate(exclusive.colour=(length(unique(Pack))==1))
根据您的数据,请注意PURPLE
的预期结果应为FALSE
,因为它位于Pack
s C
和D
中:
print(res)
##Source: local data frame [19 x 3]
##Groups: colour [11]
##
## Pack colour exclusive.colour
## <fctr> <fctr> <lgl>
##1 A WHITE FALSE
##2 A BLACK FALSE
##3 B WHITE FALSE
##4 B GREEN TRUE
##5 C WHITE FALSE
##6 C YELLOW TRUE
##7 C BLACK FALSE
##8 C PURPLE FALSE
##9 C RED TRUE
##10 C BLACK FALSE
##11 D PURPLE FALSE
##12 D BLUE TRUE
##13 D WHITE FALSE
##14 D BROWN TRUE
##15 D ORANGE TRUE
##16 D BLACK FALSE
##17 D WHITE FALSE
##18 D LIME TRUE
##19 D PINK TRUE
数据:强>
df <- structure(list(Pack = structure(c(1L, 1L, 2L, 2L, 3L, 3L, 3L,
3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L), .Label = c("A",
"B", "C", "D"), class = "factor"), colour = structure(c(10L,
1L, 10L, 4L, 10L, 11L, 1L, 8L, 9L, 1L, 8L, 2L, 10L, 3L, 6L, 1L,
10L, 5L, 7L), .Label = c("BLACK", "BLUE", "BROWN", "GREEN", "LIME",
"ORANGE", "PINK", "PURPLE", "RED", "WHITE", "YELLOW"), class = "factor")), .Names = c("Pack",
"colour"), row.names = c(NA, -19L), class = "data.frame")
## Pack colour
##1 A WHITE
##2 A BLACK
##3 B WHITE
##4 B GREEN
##5 C WHITE
##6 C YELLOW
##7 C BLACK
##8 C PURPLE
##9 C RED
##10 C BLACK
##11 D PURPLE
##12 D BLUE
##13 D WHITE
##14 D BROWN
##15 D ORANGE
##16 D BLACK
##17 D WHITE
##18 D LIME
##19 D PINK
答案 1 :(得分:1)
答案 2 :(得分:0)
这个怎么样。
set.seed(12)
#generate data. Instead of colours I have upper case letters
d <- data.frame(pack = rep(letters[1:6], each = 5),
colour = sample(LETTERS[1:10], 30, replace = TRUE),
exclusivecolour = NA)
# For each item in column 'colour', get all items in column 'pack' with that colour.
# If there is 1 unique value, it is exclusive.
d$exclusivecolour <- sapply(d$colour, function(x) length(unique(d$pack[d$colour == x])) == 1)