【发布时间】:2019-05-25 15:11:52
【问题描述】:
我正在使用 iris 数据集,并对其进行如下操作以获得物种、特征1、特征2、值数据框:
gatherpairs <- function(data, ...,
xkey = '.xkey', xvalue = '.xvalue',
ykey = '.ykey', yvalue = '.yvalue',
na.rm = FALSE, convert = FALSE, factor_key = FALSE) {
vars <- quos(...)
xkey <- enquo(xkey)
xvalue <- enquo(xvalue)
ykey <- enquo(ykey)
yvalue <- enquo(yvalue)
data %>% {
cbind(gather(., key = !!xkey, value = !!xvalue, !!!vars,
na.rm = na.rm, convert = convert, factor_key = factor_key),
select(., !!!vars))
} %>% gather(., key = !!ykey, value = !!yvalue, !!!vars,
na.rm = na.rm, convert = convert, factor_key = factor_key)%>%
filter(!(.xkey == .ykey)) %>%
mutate(var = apply(.[, c(".xkey", ".ykey")], 1, function(x) paste(sort(x), collapse = ""))) %>%
arrange(var)
}
test = iris %>%
gatherpairs(sapply(colnames(iris[, -ncol(iris)]), eval))
这取自https://stackoverflow.com/a/47731111/8315659
这样做是为我提供了包含 feature1 和 feature2 的所有组合的数据框,但我想删除只是显示相反的重复项。例如,Petal.Length vs Petal.Width 与 Petal.Width vs Petal.Length 相同。但是,如果有两行 Petal.Length 和 Petal.Width 的值相同,我不想删除该行。因此,只是删除所有值都相同的行,除了 .xkey 和 .ykey 被颠倒是我想要做的。本质上,这只是为了重新创建上面链接答案中显示的 ggplot 矩阵的底部三角形。
如何做到这一点? 杰克
【问题讨论】: