代码之家  ›  专栏  ›  技术社区  ›  Jack Arnestad

仅当两列中的值反转且所有其他值相同时,才在数据框中删除行

  •  0
  • Jack Arnestad  · 技术社区  · 6 年前

    我正在使用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

    如何做到这一点? 杰克

    1 回复  |  直到 6 年前
        1
  •  0
  •   Jon Spring    6 年前

    我认为这可以通过使用源代码的第一部分来完成,该部分执行单个收集操作。使用 iris 例如,这将生成600行输出,其中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)
    }