0

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 function I am using:

df <- data.frame(cs=rep(c("T1","T2","T3","T4"),each=16),yr=rep(c(1:4), times = 4, each = 4))
sp.df <- data.frame(matrix(sample.int(100, size = 20*64,replace=T), ncol = 20, nrow = 64))

myfunc<-function(X,  system, Title)
{
  for(i in 1:4){
    Col_T <- data.frame(matrix(NA, ncol = length(X), nrow = 4))
    Col_T[i,] <- colSums(X[which(df$yr==i & df$cs==system),])
    return (Col_T)}}

myfunc(X=sp.df, system="T1", Title="T1")

I would welcome any suggestion to resolve this issue. Thank you very much.

1 Answer 1

2

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);
};
Sign up to request clarification or add additional context in comments.

3 Comments

Your use of semicolon in R is very rare, but not incorrect. Why do you use it?
@MrGumble, It has always been my programming style to explicitly terminate every statement with a semicolon in many languages (R/JavaScript/SQL/bash) in contexts where they are not essential. Perhaps it's a carryover from my C/C++/Java experience, but I feel it helps make the code more readable and more clearcut, kind of like the programmer is explicitly stating that the statement is complete. Also, semicolons are required when coding multiple statements on the same line, so you could say it improves consistency as well.
@bgoldst I would really like to, but apparently my reputation is not high enough to upvote :(, sorry for that.

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.