1

I have a list, listDFs, where each element is a data frame. Each data frame has a different number of rows and the same number of columns.

I should create a vector beginning from listDFs[[i]]$Name extracting all the i element from the list.

I thought to use a loop such:

vComposti <- c()
for(j in 1:10){vComposti <- c(listDFs[[j]]$Name)}

But the result is a vector containing only the first level (listDFs[[1]]$Name) of the list.

Where I wrong?? Do you have any suggestion??

1 Answer 1

6

The problem you have is in this line:

vComposti <- c(listDFs[[j]]$Name)

Each time through your loop, you are re-assigning a new value to vComposti and overwriting the previous value.

In general it is preferable to pre-allocate the vector and fill it element by element:

vComposti <- rep(NA, 10)
for(j in 1:10){
    vComposti[j] <- c(listDFs[[j]]$Name)
}

But it's also not clear to me exactly what you're expecting the result to be. You create a vector, but it looks like you are trying to store an entire data frame column in each element of the vector. If that's the case you may actually be looking for a result that's a list:

vComposti <- vector("list",10)
for(j in 1:10){
    vComposti[[j]] <- c(listDFs[[j]]$Name)
}

Another, somewhat more sophisticated, option may be to use lapply:

lapply(listDFs,FUN = "[","Name")
Sign up to request clarification or add additional context in comments.

4 Comments

Yes, lapply is the best choice but, the return of lapply is a list . How should I do to transform it in a data frame?
@Riccardo, since a data.frame is a list, you can simply use as.data.frame on the result of lapply
I tried it but the R console give this error: Error in data.frame(list(Name = c("A",: arguments imply differing number of rows: 61, 57, 58, 56, 55, 53, 54, 51, 52, 48 .
I solved the last problem with this: df <-data.frame(matrix(unlist(lComposti),byrow=T))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.