R create a vector with loop structure

前端 未结 1 1973
灰色年华
灰色年华 2020-12-11 12:52

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 crea

相关标签:
1条回答
  • 2020-12-11 13:05

    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")
    
    0 讨论(0)
提交回复
热议问题