简体   繁体   中英

How to add columns just to specific rows in dataframe

I have tree dataframes:

a:
        tag1    adj.P.Val1 DE1 
1     A1BG-AS1   0.9869732  0 
2        A2LD1   0.9924706  0 
3       A4GALT   0.9538785  0 

b:
        tag2    adj.P.Val2 DE2 
1         A1BG   0.9734810  0 
2     A1BG-AS1   0.7790235  0 
3        A2LD1   0.4763385  0 

c:
        tag3    adj.P.Val3 DE3 
1     A1BG-AS1   0.9742065  0 
2        A2LD1   0.2733337  0  
3         AAAS   0.2015485  0  

I want to merge these dataframe and it is important for me that the rows with same "tag" value placed in the same row in final dataframe:

    tag1    adj.P.Val1 DE1    tag2    adj.P.Val2 DE2  tag3   adj.P.Val3   DE3
1    NA          NA    NA     A1BG      0.9734810  0   NA         NA       NA
2  1BG-AS1   0.9869732  0     A1BG-AS1  0.7790235  0  A1BG-AS1   0.9742065  0
3    A2LD1   0.9924706  0     A2LD1     0.4763385  0   A2LD1     0.2733337  0
4   A4GALT   0.9538785  0      NA          NA      NA   NA        NA       NA
5    NA          NA    NA      NA          NA      NA  AAAS      0.2015485  0

What should I do?

This should give you want you want:

# rename the id-columns & wrap put the datafrmes in a list
lst <- lapply(list(a,b,c), function(x) {names(x)[1] <- "tag";x})
# merge the three separate dataframes into one
df <- Reduce(function(...) merge(..., all = TRUE, by = "tag"), lst)

this results in:

> df
       tag adj.P.Val1 DE1 adj.P.Val2 DE2 adj.P.Val3 DE3
1 A1BG-AS1  0.9869732   0  0.7790235   0  0.9742065   0
2    A2LD1  0.9924706   0  0.4763385   0  0.2733337   0
3   A4GALT  0.9538785   0         NA  NA         NA  NA
4     A1BG         NA  NA  0.9734810   0         NA  NA
5     AAAS         NA  NA         NA  NA  0.2015485   0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM