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

亡梦爱人 提交于 2019-12-19 10:47:29

问题


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

Are there any value on X or Y (i.e., 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 (e.g., 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 

回答1:


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



回答2:


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



回答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 


来源:https://stackoverflow.com/questions/58794604/find-variables-that-occur-only-in-one-cluster-in-data-frame-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!