1

I have created a function to call a function on each row in a dataset. I would like to have the output as a vector. As you can see below the function outputs the results to the screen, but I cannot figure out how to redirect the output to a vector that I can use outside the function.

n_markers <- nrow(data)
p_values <-rep(0, n_markers)

test_markers <- function()
   {
   for (i in 1:n_markers)
      {
      hets  <- data[i, 2]
      hom_1 <- data[i, 3]
      hom_2 <- data[i, 4]   
      p_values[i] <- SNPHWE(hets, hom_1, hom_2)
      }
      return(p_values)
   }

test_markers()
Keith W. Larson
  • 1,543
  • 2
  • 19
  • 34
  • 3
    1. You should get in the habit of passing your functions arguments rather than relying on globals (c.f. http://stackoverflow.com/questions/5526322/examples-of-the-perils-of-globals-in-r-and-stata ). 2. There's already a function to do that. Look at `apply(my.data, 1, ...)` – Ari B. Friedman May 03 '12 at 13:20
  • `shinyNewVector <- test_markers()`. Do heed the advice from gsk3 too. – Chase May 03 '12 at 13:32
  • 1
    Read a basic introduction to R as well. You need to switch your mentality to thinking in vectors instead of for loops. – Hansi May 03 '12 at 13:33
  • 2
    I agree Hansi et al., but I also have to balance the demands of finishing my PhD with becoming a great R programmer. That is why I so much appreciate this site and its contributors! – Keith W. Larson May 03 '12 at 14:28

1 Answers1

4

Did you just take this code from here? I worry that you didn't even try to figure it out on your own first, but hopefully I am wrong.

You might be overthinking this. Simply store the results of your function in a vector like you do with other functions:

stored_vector <- test_markers()

But, as mentioned in the comments, your function could probably be reduced to:

stored_vector <- sapply(1:nrow(data), function(i) SNPHWE(data[i,2],data[i,3],data[i,4]) )
nograpes
  • 18,623
  • 1
  • 44
  • 67