Home > Blockchain >  merge the data frame list with the headers
merge the data frame list with the headers

Time:11-15

I have a list that stores 2 data frames

data <- list(structure(list(GROUP = "3\nN=6 (86%)", col1 = "6.5 [5.25; 7.75]", 
    col2 = "9 [7.25; 10.75]", col3 = "10.5 [9.25; 11.75]", dif = "1-2: -3 [-3; -3]\n1-3: -5 [-5; -5]\n2-3: -2 [-2; -2]", 
    p.value = "1-2: 0.107\n1-3: 0.013*\n2-3: 0.295"), row.names = c(NA, 
-1L), class = "data.frame"), structure(list(GROUP = "3\nN=6 (86%)", 
    col3 = "10.5 [9.25; 11.75]", col4 = "14.5 [12.5; 15.75]", 
    col5 = "16.5 [15.25; 17.75]", dif = "3-4: -3 [-3; -3]\n3-5: -6 [-6; -6]\n4-5: -3 [-3; -3]", 
    p.value = "3-4: 0.030*\n3-5: 0.002*\n4-5: 0.126"), row.names = c(NA, 
-1L), class = "data.frame"))

I want to combine them to get one data frame with headers. What I expect to get:

data <- structure(list(GROUP = c("3\nN=6 (86%)", "GROUP", "3\nN=6 (86%)"
), col1 = c("6.5 [5.25; 7.75]", "col3", "10.5 [9.25; 11.75]"), 
    col2 = c("9 [7.25; 10.75]", "col4", "14.5 [12.5; 15.75]"), 
    col3 = c("10.5 [9.25; 11.75]", "col5", "16.5 [15.25; 17.75]"
    ), dif = c("1-2: -3 [-3; -3]\n1-3: -5 [-5; -5]\n2-3: -2 [-2; -2]", 
    "dif", "3-4: -3 [-3; -3]\n3-5: -6 [-6; -6]\n4-5: -3 [-3; -3]"
    ), p.value = c("1-2: 0.107\n1-3: 0.013*\n2-3: 0.295", "p.value", 
    "3-4: 0.030*\n3-5: 0.002*\n4-5: 0.126")), row.names = c(NA, 
-3L), class = "data.frame")

I tried to use:

rbindlist(data);
do.call(rbind;data)
lapply(data, setNames, names(data))

but none of this helped me

CodePudding user response:

Use do call

Then convert the first row to column and thereafter delete first row

tt<- do.call(rbind.data.frame, lapply(data, function(x) unname(rbind(names(x), as.matrix(x)))))
names(tt) <- tt[1,]
tt <- tt[-1,]
  • Related