根据来自另一个数据帧的值向数据帧添加一列

时间:2021-03-04 10:55:05

标签: r dataframe if-statement match data-science

我有一个包含 1 列 test 的数据框 exposure

    exposure                       
1    CD177 
2    RFESD 
3    IL12B                       
4   IL18R1 
5      CEL

我想根据下面另一个数据框 test 中的列 count_typetest1 添加一列

  Exposure cis.trans count_type
 1:    CD177       cis          1
 2:    CD177       cis          1
 3:    CD177       cis          1
 4:    CD177       cis          1
 5:    CD177       cis          1
 6:    CD177       cis          1
 7:    CD177       cis          1
 8:      CEL       cis          1
 9:    IL12B     trans          2
10:    IL12B       cis          2
11:   IL18R1       cis          1
12:   IL18R1       cis          1
13:   IL18R1       cis          1
14:    RFESD       cis          1

if count_type =1 我想从 cis.trans 列中获取值,否则该值将是 "mix" 在这个例子中,我想得到这个:

 exposure  typ
1    CD177 cis 
2    RFESD cis 
3    IL12B mix
4   IL18R1 cis
5      CEL cis

这是我的代码:

test<-test%>%
  mutate( typ=ifelse(test1[match(test$exposure,test1$Exposure),"count_type"]==1,
                     test1[match(test$exposure,test1$Exposure),"cis.trans"],
                     "mix"))

我得到的是以下内容:

exposure                       typ
1    CD177 cis, cis, trans, cis, cis
2    RFESD cis, cis, trans, cis, cis
3    IL12B                       mix
4   IL18R1 cis, cis, trans, cis, cis
5      CEL cis, cis, trans, cis, cis

我不知道问题出在哪里我尝试了以下操作来测试返回的匹配项,它确实返回了 test1 数据帧中所需值的索引

test<-test%>%
  mutate( typ_ind=ifelse(test1[match(test$exposure,test1$Exposure),"count_type"]==1,
                     match(test$exposure,test1$Exposure),
                     "mix"))

test
  exposure                       typ count_type
1    CD177 cis, cis, trans, cis, cis          1
2    RFESD cis, cis, trans, cis, cis         14
3    IL12B                       mix        mix
4   IL18R1 cis, cis, trans, cis, cis         11
5      CEL cis, cis, trans, cis, cis          8

知道发生了什么以及如何解决吗?

1 个答案:

答案 0 :(得分:1)

仅保留基于 test1Exposure 列的 count_type 的唯一行,并使用 test 连接数据。如果 cis.trans,请将 "mix" 的值更改为 count_type = 2

library(dplyr)

test1 %>%
  distinct(Exposure, count_type, .keep_all = TRUE) %>%
  inner_join(test, by = c('Exposure' = 'exposure')) %>%
  mutate(cis.trans  = ifelse(count_type == 2, 'mix', cis.trans))

#  Exposure cis.trans count_type
#1    CD177       cis          1
#2      CEL       cis          1
#3    IL12B       mix          2
#4   IL18R1       cis          1
#5    RFESD       cis          1
相关问题