Reputation: 7517
I have a list of 3 vectors, X
, Y
, and Z
. I was wondering how I could delete elements that appear only once (here ChandlerA
and Trus.Hsu
) across all 3 vectors?
d = list(X = c(Bit.KnoA = 4, Bit.KnoB = 1, Bit.KnoC = 2, ChandlerA = 3, Ellis.etal =4,
Mubarak=5, SheenA=6, Shin.Ellis=7 , Sun = 8, Trus.Hsu=3 ),
Y = c(Bit.KnoA = 6, Bit.KnoB = 3, Bit.KnoC = 4, Ellis.etal =1, Mubarak=2,
SheenA=1, Shin.Ellis=2 , Sun = 1),
Z = c(Bit.KnoB = 2) )
Upvotes: 3
Views: 474
Reputation: 93813
You could also use duplicated
since you're only interested in the loner values:
nms <- unlist(lapply(d, names))
keep <- nms[duplicated(nms)]
lapply(d, function(x) x[names(x) %in% keep] )
#$X
# Bit.KnoA Bit.KnoB Bit.KnoC Ellis.etal Mubarak SheenA Shin.Ellis Sun
# 4 1 2 4 5 6 7 8
#
#$Y
# Bit.KnoA Bit.KnoB Bit.KnoC Ellis.etal Mubarak SheenA Shin.Ellis Sun
# 6 3 4 1 2 1 2 1
#
#$Z
#Bit.KnoB
# 2
Upvotes: 3
Reputation: 388947
We could create a copy of d
, remove it's names so that when we unlist
the names of the list names are not prepended to the vector. Count number of occurrence of each name in the list and select names
of those who occur only once and remove them from original list (d
).
d1 <- d
names(d1) <- NULL
vals <- table(names(unlist(d1)))
delete_names <- names(vals[vals == 1])
lapply(d, function(x) x[setdiff(names(x), delete_names)])
#$X
# Bit.KnoA Bit.KnoB Bit.KnoC Ellis.etal Mubarak SheenA Shin.Ellis Sun
# 4 1 2 4 5 6 7 8
#$Y
# Bit.KnoA Bit.KnoB Bit.KnoC Ellis.etal Mubarak SheenA Shin.Ellis Sun
# 6 3 4 1 2 1 2 1
#$Z
#Bit.KnoB
# 2
Upvotes: 3