How to join data from 2 different csv-files in R?

后端 未结 2 1613
孤街浪徒
孤街浪徒 2021-01-07 02:57

I have the following problem: in a csv-file I have a column for species, one for transect, one for the year and one for the AUC. In another csv-file I have a column for tran

2条回答
  •  生来不讨喜
    2021-01-07 03:26

    Use read.csv and then merge.

    Load the two csv files into R. (Don't forget to make sure their common variables share the same name!).

    df1<-read.csv(dat1,head=T)
    df2<-read.csv(dat2,head=T)
    

    Merge the dataframes together by their shared variables and add argument all.x=T (the default) to ensure all rows are kept from your database containing species.

    merge(df1,df2,by=c('transect_id','year'),all.x=T)
    

    To see this in action using test data:

    test<-data.frame(sp=c(rep(letters[1:10],2)),t=c(rep(1:3,2,20)),y=c(rep(2000:2008,len=20)),AUC=1:20)
    test2<-data.frame(t=c(rep(1:3,2,9)),y=c(rep(2000:2008,len=9)),ppt=c(1:9),temp=c(11:19))
    
    merge(test,test2,by=c('t','y'),all.x=T)
    

提交回复
热议问题