Using user-defined “for loop” function to construct a data frame

后端 未结 1 397
再見小時候
再見小時候 2020-12-07 06:08

I am trying to generate a data frame based on a user-defined function. My problem is that in the output only the first row is being filled. Here is an example of the functi

相关标签:
1条回答
  • 2020-12-07 06:39

    There are two problems with the function:

    1. You're overwriting Col_T with all NAs as the first statement inside the for loop.
    2. You're returning from the function inside the for loop.

    Rewrite it as follows:

    myfunc <- function(X, system, Title ) {
        Col_T <- data.frame(matrix(NA, ncol=length(X), nrow=4 ));
        for (i in 1:4)
            Col_T[i,] <- colSums(X[which(df$yr==i & df$cs==system),]);
        return(Col_T);
    };
    
    0 讨论(0)
提交回复
热议问题