3

I want to fetch some values out of a list of data frames and save the results in a new data frame. This is how my code looks:

for (i in 1:length(covpatient)){

    a <- names(covpatient[i])
    b <- sum(covpatient[[i]]$cov == 0)
    c <- sum(covpatient[[i]]$cov > 0 & covpatient[[i]]$cov <= 40)
    d <- sum(covpatient[[i]]$cov > 40 & covpatient[[i]]$cov <= 100)
    e <- sum(covpatient[[i]]$cov > 100)
    summary <- c(a,b,c,d,e)

}

So for every dataframe in the list covpatient, I want to create a summary variable which consists of 5 elements (a,b,c,d,e). Then I want to make a new data.frame which stores all summary values (5 columns & i rows).

Could someone give me a hand?

1 Answer 1

4

One way is to use lapply with rbind and then call as.data.frame. Since there is no data to play with, I'll give the general idea.

o <- lapply(1:length(covpatient), function(i) {
    a <- names(covpatient[i])
    b <- sum(covpatient[[i]]$cov == 0)
    c <- sum(covpatient[[i]]$cov > 0 & covpatient[[i]]$cov <= 40)
    d <- sum(covpatient[[i]]$cov > 40 & covpatient[[i]]$cov <= 100)
    e <- sum(covpatient[[i]]$cov > 100)
    c(a,b,c,d,e)
})
out <- as.data.frame(do.call(rbind, o))
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, that I understand. But when I try to run it, it says: "Error unexpected symbol in: " out"
Arun has the exact answer to your question. Using 'lapply' over the set and then binding will do what you want. I have a feeling, though, that this could be done more simply by backing up a few steps and arranging your data differently. This feels like something that should be done with an aggregation package like 'plyr', 'data.table', or even 'SPARQL'.

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.