【问题标题】:matching values in different columns of a dataframe in r [duplicate]匹配r中数据框不同列中的值[重复]
【发布时间】:2020-10-25 23:46:44
【问题描述】:

数据框:

     A  B 
1    a  c
2    x  x
3    t  q
4    l  l
5    w  y
6    b  b

我想添加一个检测匹配或不匹配的列:

     A  B  C 
1    a  c  miss
2    x  x  match
3    t  q  miss
4    l  l  match
5    w  y  miss
6    b  b  match

【问题讨论】:

  • df$C <- ifelse(df$A == df$B, 'match', 'miss')

标签: r dataframe


【解决方案1】:

基本 R 选项

transform(
  df,
  C = c("miss","match")[(A==B)+1]
)

给予

  A B     C
1 a c  miss
2 x x match
3 t q  miss
4 l l match
5 w y  miss
6 b b match

数据

> dput(df)
structure(list(A = c("a", "x", "t", "l", "w", "b"), B = c("c", 
"x", "q", "l", "y", "b")), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))

【讨论】:

    【解决方案2】:
    > dd %>% rowwise() %>% mutate(match = case_when(A == B ~ 'match', TRUE ~ 'miss'))
    # A tibble: 6 x 3
    # Rowwise: 
      A     B     match
      <chr> <chr> <chr>
    1 a     c     miss 
    2 x     x     match
    3 t     q     miss 
    4 l     l     match
    5 w     y     miss 
    6 b     b     match
    > dd
    # A tibble: 6 x 2
      A     B    
      <chr> <chr>
    1 a     c    
    2 x     x    
    3 t     q    
    4 l     l    
    5 w     y    
    6 b     b    
    > 
    

    【讨论】:

      【解决方案3】:

      带有索引的base R 选项(虽然@ThomasIsCoding 是更专业的解决方案):

      #Code
      index <- df$A==df$B
      df$C <- 'miss'
      df$C[index]<-'match'
      

      输出:

      df
        A B     C
      1 a c  miss
      2 x x match
      3 t q  miss
      4 l l match
      5 w y  miss
      6 b b match
      

      使用的一些数据:

      #Data
      df <- structure(list(A = c("a", "x", "t", "l", "w", "b"), B = c("c", 
      "x", "q", "l", "y", "b")), class = "data.frame", row.names = c("1", 
      "2", "3", "4", "5", "6"))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-13
        • 2017-01-06
        • 1970-01-01
        • 2021-10-01
        • 1970-01-01
        相关资源
        最近更新 更多