Arnav Harkenavvy
Arnav Harkenavvy

Reputation: 115

How do I return a vector from a for loop in R?

Suppose I have the following code:

f <- function(da) {
      v <- numeric(length(unique(da$cyl)))
      for (i in unique(mtcars$cyl)) { 
        each_cylValue_df <- mtcars[mtcars$cyl==i,]
        medianMPG <- median(each_cylValue_df$mpg)
        v[i] <- medianMPG
      }
      v
    }
    f(mtcars)

I am trying to use a function to capture the results of a for loop which iterates three times. My intended output is a vector of the median mpg value of the three iterated cyl values in the mtcars data frame, ideally returning the vector (19.7, 26, 15.2). However, when I run the above code, it returns a vector of the proper length, three, but it returns all zeroes. What is the fix to this issue?

Upvotes: 1

Views: 348

Answers (1)

akrun
akrun

Reputation: 887048

We don't need a loop. It can be done in a group by operation

aggregate(mpg ~ cyl, mtcars, median)
#   cyl  mpg
#1   4 26.0
#2   6 19.7
#3   8 15.2

Or a vector with tapply

with(mtcars, tapply(mpg, cyl, median))

Upvotes: 3

Related Questions