Amaranta_Remedios
Amaranta_Remedios

Reputation: 773

Concatenate multiple df in list into different columns of a single df

I have a list of dataframes(df1) in R made of 40 dataframes, each with only 1 column (V1). I want to concatenate all the dataframes in df1 into a single dataframe (df2) where each dataframe in df1 has become just a column in df2.

So far I am doing this:

df2 <- bind_rows(df1, .id = "column_label")

head(df2)   
column_label         V1
Hazt              miR-92
Hazt              miR-92
Hazt              miR-92
Hazt              miR-184
Hazt              miR-184
PPee              miR-92
PPee              miR-3

However, as stated before I wish the new dataframe looked like this instead

Hazt       PPee 
miR-92     miR-92
miR-92     miR-3
miR-92
miR-184
miR-184

With as many columns as originals dataframes where in df1.

Upvotes: 1

Views: 72

Answers (4)

Marcos P&#233;rez
Marcos P&#233;rez

Reputation: 1250

If df1 is a list, then try this:

df2 <- do.call("cbind",df1)

If you have data frames with diferent number of rows, Try this:

df1 <- lapply(df1, function(x,n){if(nrow(x)<n){x[n,]<-NA};return(x)},n = max(sapply(df1,nrow)))

do.call("cbind",df1)

Upvotes: 3

Ronak Shah
Ronak Shah

Reputation: 388982

In base R, you could split the data based on column_label column and then create a dataframe by appending it NAs.

tmp <- split(df2$V1, df2$column_label)
sapply(tmp, `[`, 1:max(lengths(tmp)))

#         Hazt      PPee    
#[1,] "miR-92"  "miR-92"
#[2,] "miR-92"  "miR-3" 
#[3,] "miR-92"  NA      
#[4,] "miR-184" NA      
#[5,] "miR-184" NA      

Upvotes: 1

ThomasIsCoding
ThomasIsCoding

Reputation: 101337

A base R option using list2DF + unstack

> list2DF(lapply(u <- unstack(rev(df2)), `length<-`, max(lengths(u))))
     Hazt   PPee
1  miR-92 miR-92
2  miR-92  miR-3
3  miR-92   <NA>
4 miR-184   <NA>
5 miR-184   <NA>

Upvotes: 2

akrun
akrun

Reputation: 887098

We can use pivot_wider

library(dplyr)
library(tidyr)
library(data.table)
df2 %>% 
    mutate(rn = rowid(column_label)) %>%
    pivot_wider(names_from = column_label, values_from = V1, values_fill = "") %>%
    select(-rn)

-output

# A tibble: 5 x 2
#  Hazt    PPee    
#  <chr>   <chr>   
#1 miR-92  "miR-92"
#2 miR-92  "miR-3" 
#3 miR-92  ""      
#4 miR-184 ""      
#5 miR-184 ""      

data

df2 <- structure(list(column_label = c("Hazt", "Hazt", "Hazt", "Hazt", 
"Hazt", "PPee", "PPee"), V1 = c("miR-92", "miR-92", "miR-92", 
"miR-184", "miR-184", "miR-92", "miR-3")), class = "data.frame",
row.names = c(NA, 
-7L))

Upvotes: 1

Related Questions