简体   繁体   中英

Find variables that occur only in one cluster in data.frame in R

Using BASE R, I wonder how to answer the following question:

Are there any value on X or Y (ie, variables of interest names) that occurs only in one element in m (as a cluster) but not others? If yes, produce my desired output below.

For example: Here we see X == 3 only occurs in element m[[3]] but not m[[1]] and m[[2]] . Here we also see Y == 99 only occur in m[[1]] but not others.

Note: the following is a toy example, a functional answer is appreciated. AND X & Y may or may not be numeric (eg, be string).

f <- data.frame(id = c(rep("AA",4), rep("BB",2), rep("CC",2)), X = c(1,1,1,1,1,1,3,3), 
            Y = c(99,99,99,99,6,6,6,6))

m <- split(f, f$id) # Here is `m`

mods <- names(f)[-1] # variables of interest names

Desired output:

list(AA = c(Y = 99), CC = c(X = 3))

# $AA
# Y 
# 99 

# $CC
# X 
# 3 

This is a solution based on rapply() and table() .

ux <- rapply(m, unique)
tb <- table(uxm <- ux[gsub(rx <- "^.*\\.(.*)$", "\\1", names(ux)) %in% mods])
r <- Map(setNames, n <- uxm[uxm %in% names(tb)[tb == 1]], gsub(rx, "\\1", names(n)))
setNames(r, gsub("^(.*)\\..*$", "\\1", names(r)))
# $AA
# Y 
# 99 
# 
# $CC
# X 
# 3
tmp = do.call(rbind, lapply(names(f)[-1], function(x){
    d = unique(f[c("id", x)])
    names(d) = c("id", "val")
    transform(d, nm = x)
}))

tmp = tmp[ave(as.numeric(as.factor(tmp$val)), tmp$val, FUN = length) == 1,]

lapply(split(tmp, tmp$id), function(a){
    setNames(a$val, a$nm)
})
#$AA
# Y 
#99 

#$BB
#named numeric(0)

#$CC
#X 
#3

This utilizes @jay.sf's idea of rapply() with an idea from a previous answer :

vec <- rapply(lapply(m, '[', , mods), unique)
unique_vec <- vec[!duplicated(vec) & !duplicated(vec, fromLast = T)]

vec_names <- do.call(rbind, strsplit(names(unique_vec), '.', fixed = T))
names(unique_vec) <- vec_names[, 2]

split(unique_vec, vec_names[, 1])

$AA
 Y 
99 

$CC
X 
3 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM