rsc05 rsc05 - 1 month ago 6
R Question

How to convert a list into a data frame while keeping its headers in R

I have a a list called

mylist
, in it there are 108 rows apart from the headers. I tried converting it to a dataframe and it successfully worked using the following command

df <- data.frame(matrix(unlist(mylist), nrow=108, byrow=F))


However, the headers for each matrix in my list (mylist) have not been defined in my new dataframe df.

names(df)


is

"X1" "X2" "X3" "X4" "X5" "X6" "X7" "X8" "X9" "X10" "X11" "X12" "X13" "X14" "X15" "X16" "X17" "X18" "X19" "X20" "X21" "X22" "X23" "X24" "X25" "X26" "X27" "X28" "X29" "X30" "X31" "X32" "X33" "X34" "X35" "X36"


mylist
looks something like so

head(mylist[[1]])

RAmi MDaf
1 11.806405 -3.588567
2 7.711101 -9.721415
3 2.315104 11.217575
4 20.372999 -2.267938
5 22.279704 -1.668082
6 13.57909 20.67355



head(mylist[[2]])

Tomi Rahaf
1 325 -3
2 71 -9
3 2 11
4 20.999 -22
5 22 -16
6 139 2065


this is only for
head(mylist[[i]])
when
i=1
but there exist similar things for i=1,2,3, ... , 18

What I want is to put them all in one dataframe adjacently. It worked fine but I am having a problem with the heading

I hope one may help me with understanding how to do so.
Thank you

Answer

It seems that there is a problem in converting a list of dataframes into one dataframe. Therefore, it would be better to work with one dataframe from the very beginning.

For example, in my case i imported the raw data

#data1=read.csv(file.choose(), header=F)
data1=read.csv

Then afterwards I started analysing my data. I then wrote a code to generate a dataframe as in

# Here we are extracting the data which we wish to have
#iterations=nrow(data1) #Check the number of rows

listOfDataFrames <- vector(mode = "list", length = 18)   # define a dataframe with length
#mylist <- list() #create an empty list
for (k in 0:17)
{
    j=18 # from 14 i.e. switzerland this is not true anymore 
    if ((k>=14) && (k<16))
    {
        f=7+j*k
        s=3+j*k

    }  else if (k<14)
    {
        s=7+j*k-4
        f=7+j*k
    } else if (k==16)
    {
        f=j*k+5
        s=f+4
    } else if (k==17)
    {
        f=304
        s=301
    }
    b= data1[,c(f,s)] 
    #mylist[[k+1]] <- b
    listOfDataFrames[[k+1]]=b
}
#df <- data.frame(matrix(unlist(mylist), nrow=108, byrow=F))

This allowed me to put all the data into one dataframe along with the headers

df=do.call("cbind", listOfDataFrames)
head(df)
Comments