代码之家  ›  专栏  ›  技术社区  ›  ip2018

条件搜索、匹配、过滤和替换数据帧之间的值

  •  0
  • ip2018  · 技术社区  · 7 年前

    input_1 = data.frame(col1 = c("ex1", "ex2", "ex3", "ex4"), col2 = c(1.2, 1.6, 1.9, 0.8), col3 = c(2.1, 0.8, 2.8, 1.9))

    input_2 = data.frame(col1 = c("ex1", "ex2", "ex3", "ex4"), col2 = c(0.07, 0.06, 0.05, 0.03), col3 = c(0.05, 0.06, 0.08, 0.07))

    output = data.frame(col1 = c("ex1", "ex2", "ex3", "ex4"), col2 = c(NA, NA, 1.9, 0.8), col3 = c(2.1, NA, NA, NA))

    2 回复  |  直到 7 年前
        1
  •  1
  •   nsinghphd    7 年前

    只使用带基的索引 R 这可以用下面的一行来完成。我建议你先用 stringsAsFactors = F data.frame 函数,这也是将来数据读入的好做法 R

    input_1[-1][input_2[-1] > 0.05] = NA
    

    input_1 如果要保留原始对象,则可以预先创建另一个对象。 [-1] 排除第一列。

        2
  •  1
  •   John Nielsen    7 年前

    对于您的特定问题,我能想到的最短和最简单的解决方案是使用 which()

    output[which(input_2$col2 > 0.05),2] <- NA
    output[which(input_2$col3 > 0.05),3] <- NA
    

    哪个() TRUE 逻辑向量或数组中的值。通过设置列( input_2$col2 )在逻辑上与一个值相反, R 在向量中的所有值上测试此假设,并返回 真的 FALSE 对于向量中的每个值。当你把这个和 哪个() 函数并在数据帧中的向量或列/行的子集中使用,您将从符合逻辑测试的向量/列/行中获取值。这是在数据帧中设置条件值的一种简单方法。

    ifelse() 内部函数 mutate()

    threshold <- 0.5
    df <- input_1 %>% 
      mutate(new_col = ifelse(col2 > threshold, NA, col2))
    

    希望有帮助。如果你对 R 那么请阅读哈德利·威克姆的书: https://r4ds.had.co.nz/index.html

        3
  •  0
  •   Felipe Alvarenga    7 年前

    基本进近,不是很有效

    dt <- merge(input_1, input_2, by = 'col1', suffixes = c('_1', '_2'))
    dt$col2_1[dt$col2_2 <= 0.05] <- NA
    dt$col3_1[dt$col3_2 <= 0.05] <- NA
    
    dt$col2_2 <- NULL
    dt$col3_2 <- NULL
    
      col1 col2_1 col3_1
    1  ex1    1.2     NA
    2  ex2    1.6    0.8
    3  ex3     NA    2.8
    4  ex4     NA    1.9
    
        4
  •  0
  •   NM_    7 年前
    output = input_1
    output[input_2[,"col2"] > 0.05 , "col2"] = NA
    output[input_2[,"col3"] > 0.05 , "col3"] = NA
    
    > output
      col1 col2 col3
    1  ex1   NA  2.1
    2  ex2   NA   NA
    3  ex3  1.9   NA
    4  ex4  0.8   NA