【问题标题】:How to combine dataframes in R如何在 R 中组合数据框
【发布时间】:2018-07-30 14:38:06
【问题描述】:

我想将两个数据帧合并到一个新的数据帧中,其中包含两个数据帧中的列,此外,我需要在新数据帧中只放入具有相同 ID 的行。

我的数据框看起来像:

df1
Name       V1  V2   V3
str1       .   .    strA    
str2       .   .    strB
..         .   . 
str16000   .   .    strC


df2
Name       V1  V2   V3
str2       .   .    strD    
str1       .   .    strE
..         .   . 
str20000   .   .    strF

我想要这样的输出:

Name     df1$v3    df2$v3
str1     strA      strE
str2     strB      strD

注意 df1 和 df2 有不同的长度,而且 df1 和 df2 中的相同项目的位置不同。

谢谢大家

【问题讨论】:

标签: r dataframe merge intersect


【解决方案1】:

使用合并功能

lines=
   'Name      V1  V2   V3
    str1      NA  NA   strA    
    str2      NA  NA   strB
    str16000  NA  NA   strC'

df1 = read.table(textConnection(lines), header = T)

lines=
   'Name      V1  V2   V3
    str1      NA  NA   strD    
    str2      NA  NA   strE
    str16000  NA  NA   strF'

df2 = read.table(textConnection(lines), header = T)


dfnew = merge(df1[1:2, -2:-3], df2[1:2, -2:-3], by='Name')

colnames(dfnew) = c('Name', 'df1$v3 ', 'df2$v3')

dfnew 

#  Name df1$v3  df2$v3
#1 str1    strA   strD
#2 str2    strB   strE

【讨论】:

    猜你喜欢
    • 2020-02-17
    • 1970-01-01
    • 2014-07-30
    • 2017-09-04
    • 2019-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多