【问题标题】:Reorganize and match data sets by column in R在 R 中按列重新组织和匹配数据集
【发布时间】:2019-01-15 19:47:28
【问题描述】:

这是我的第一篇文章,如有错误请见谅。

我有两个要按样本名称合并的数据集,问题是第二个数据集在样本名称中有额外的标签,并且与第一个数据集的顺序不同。

Clinical                                                                  
Patient, Cell Count                                                            
BB-01-D1    7
BB-02-D1    4
BB-04-D30   2

Flow                                                                      
Patient,          Cell Count                                                     
 2-5-19_BB-01-D1     7 
 3-15-19_BB-04-D30   2
 2-6-19_BB-02-D1     4

我想知道如果“患者”列包含部分相同的名称,是否有一种方法可以组合和匹配,或者是否有一种方法可以消除患者列中所有行中的额外标签所以我可以简单地重新排序。

提前谢谢你。

【问题讨论】:

标签: r loops merge


【解决方案1】:

这是一种可能性:

library(tidyverse)
df1<-read.table(text="Patient Cell Count                                                            
BB-01-D1    7
                BB-02-D1    4
                BB-04-D30   2",header=T,fill=T)
df1<-df1[,-ncol(df1)]
df2<-read.table(text="Patient,          Cell Count                                                     
 2-5-19_BB-01-D1     7 
                3-15-19_BB-04-D30   2
                2-6-19_BB-02-D1     4",header=T,fill=T)
df2<-df2[,-ncol(df2)]
df2<-df2 %>% 
  mutate(Patient.=str_remove_all(df2$Patient.,".*(?<=_)"))

然后从这里开始,如你所愿

cbind(df1,df2) #Cell Count labels lost due to reading errors. Will work on 
                                    #my data import
     Patient Cell  Patient. Cell
1  BB-01-D1    7   BB-01-D1    7
2  BB-02-D1    4   BB-04-D30    2
3 BB-04-D30    2   BB-02-D1    4

或:

df1<-df1 %>% 
  mutate(Patient=as.factor(Patient))
df2<-df2 %>% 
  rename(Patient=Patient.) %>% 
  mutate(Patient=as.factor(Patient))
merged<-df1 %>% 
  left_join(df2,"Patient") 
names(merged)<-c("Patient","Clinical","Flow")

结果:

 Patient      Clinical Flow
1  BB-01-D1        7    7
2  BB-02-D1        4    4
3 BB-04-D30        2    2

【讨论】:

    猜你喜欢
    • 2022-01-02
    • 1970-01-01
    • 2020-06-29
    • 1970-01-01
    • 2013-05-07
    • 2022-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多