【问题标题】:Drop rows in data frame only if values in two columns are reversed and all other values identical仅当两列中的值颠倒且所有其他值相同时才删除数据框中的行
【发布时间】: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 矩阵的底部三角形。

如何做到这一点? 杰克

【问题讨论】:

    标签: r dplyr tidyr


    【解决方案1】:

    我认为这可以使用源代码的第一部分来完成,它执行单个收集操作。使用 iris 示例,这将产生 600 行输出,iris 中的 150 行 x 4 列中的每一列。

    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)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-25
      • 1970-01-01
      • 2017-11-07
      相关资源
      最近更新 更多