-1

The problem is as follows: -I’ve got a list of 100 elements. -Each element of the list has three columns and a variable number of rows (seven, eight, twenty, etc.) The objective is to extract from each list element [[x]] the data (except the first row of three columns) as a single row and bind them all in a data frame. It doesen't matter that this generates NA's because each roww has different number of columns (I'll deal with that later)

I’ve tried a loop that runs through each element of the list extracting the desired data as a vector and then rbinds it to a data frame

# Code is kind of rudimentary

for (x in length(My.List)) {
  Temp <- My.List[[x]][2:nrow(My.List [[x]]),]
  Temp2 <- as.vector(as.matrix(Temp)) %>% as.data.frame() %>% t()
  Temp2 <- as.data.frame(Temp2)
  Final.DF[x] <- rbind.fill.matrix(Final.DF, Temp2) #tried with rbind also

}

I would expect a data frame were each row belongs to each list element and each column to the data extracted. I get the following error:

Error in [<-.data.frame(*tmp*, x, value = logical(0)) : new columns would leave holes after existing columns`

cabrerahector
  • 3,653
  • 4
  • 16
  • 27
  • 3
    [See here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) on making an R question that folks can help with. That includes a sample of data so we can actually run the code – camille Jul 23 '19 at 16:12
  • There are several things wrong here: (1) `for (x in length(My.List))` only runs once, you probably mean `seq_along(My.List)`; (2) `t(data.frame(...))` returns a matrix, so `as.data.frame` might not be needed; (3) never ever iteratively build row-wise a frame, better to pre-allocate a list and/or use `lapply`. If you edit your question and add the output from `dput(My.List[1:2])`, it would be much easier to suggest a fix for you. – r2evans Jul 23 '19 at 16:53

1 Answers1

0

This is certainly inappropriate, because you are losing information, data types for example.

Anyway, here you have a solution.

install.packages("rowr")
require(rowr)

m1<-as.data.frame(matrix(c(1,1,1,1,1,1),nrow = 2))
m2<-as.data.frame(matrix(c(2,2,2,2,2,2),nrow = 2))

l<-list(m1,m2) #Replace with your list

whatuwant<-function(l){ #A function depending on your list
l2<-list()
for (i in 1:length(l)) { 
vector<-c()
df<-l[[i]][,-1]
for (j in 1:ncol(df)) {
vector<-c(vector,df[,i])
}
l2[[i]]<-vector
}
db<-l2[[1]]
for (z in 2:length(l2)) {
db<-cbind.fill(db,l2[[z]])
}
return(t(db))
}

whatuwant(l) #Applying the function

Result:

        [,1] [,2] [,3] [,4]
object    1    1    1    1
object    2    2    2    2

Then l is your list, just replace.