简体   繁体   中英

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?

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM