derpkitty
derpkitty

Reputation: 11

r- call function inside for loop alternative

my_function <- function(n){}

result = list()
for(i in 0:59){
    result[i] = my_function(i)
}
write.csv(result, "result.csv")

New to R, read that for-loops are bad in R, so is there an alternative to what I'm doing? I'm basically trying to call my_function with a parameter that's increasing, and then write the results to a file.

Edit Sorry I didn't specify that I wanted to use some function of i as a parameter for my_function, 12 + (22*i) for example. Should I create a list of values and then called lapply with that list of values?

Upvotes: 0

Views: 1629

Answers (1)

Mako212
Mako212

Reputation: 7312

for loops are fine in R, but they're syntactically inefficient in a lot of use cases, especially simple ones. The apply family of functions usually makes a good substitute.

result <- lapply(0:59, my_function)
write.csv(result, "result.csv")

Depending on what your function's output is, you might want sapply rather than lapply.

Edit:

Per your update, you could do it as you say, creating the vector of values first, or you could just do something like:

lapply(12+(22*0:59), my_function) 

Upvotes: 2

Related Questions