匹配r中数据框不同列中的值

时间:2020-10-25 15:20:40

标签: r dataframe

数据框:

     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

3 个答案:

答案 0 :(得分: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"))

答案 1 :(得分:0)

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

答案 2 :(得分:0)

带有索引的const requestAll = async () => { return await Promise.all(requestItems.map(async url => { try { return await apiService.get(url); } catch (err) { console.log(err) } })); } 选项(虽然 @ThomasIsCoding 是更专业的解决方案):

base R

输出:

#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