首页 > 解决方案 > 根据来自另一个数据框的值向数据框添加一列

问题描述

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

    exposure                       
1    CD177 
2    RFESD 
3    IL12B                       
4   IL18R1 
5      CEL

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

  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

关于发生了什么以及如何解决它的任何想法?

标签: rdataframeif-statementmatchdata-science

解决方案


test1仅保留基于Exposure和列的唯一行,count_type并使用 连接数据test。将值更改cis.trans"mix"if 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

推荐阅读