r - 根据来自另一个数据框的值向数据框添加一列
问题描述
我有一个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
关于发生了什么以及如何解决它的任何想法?
解决方案
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
推荐阅读
- reactjs - React 头盔:Facebook 开放图谱
- django - 在 Django REST Framework 中序列化和存储 JSON 数组
- php - mysql如何获得某一天的最大值?
- r - 在帮助文件中,“...”参数背后是否有任何普遍意义或逻辑?
- prolog - 如何在prolog中将输入从L转换为[H | T]?
- android - 无法从活动中访问片段的方法 - UninitializedPropertyAccessException
- java - 如何将 SQL 日期时间戳转换为人类可读的时间?
- c++ - OpenGL 4.5 着色器未加载
- assembly - 从驱动器读取扇区失败
- bots - 我怎样才能在我的机器人中做到这一点?