r/R_Programming • u/moonwriter • Mar 20 '16
Curly Brackets within functions
I’ve come across functions with the following format x({…}) instead of just x( ). As an example:
suppressWarnings({ yahoo_answer <- tryCatch({ getSymbols(ticker, src = "yahoo") }, error = function(err) { NA }) })
Here suppressWarnings is a function, but inside of it is code enclosed by curly brackets.
Here’s another example:
results <- read.table("data/Ticker_List.csv", stringsAsFactors = FALSE) %>% set_colnames("ticker") %>% rowwise() %>% do({ .ticker <- .$ticker processTicker(ticker = .ticker, avg_days = 63, percentile = 0.95) }) %>% ungroup()
The internals of the do function are enclosed in curly brackets.
What is the purpose of the curly brackets within functions. I have an idea of how and why it works here in particular, but I don’t know enough to generalize this and put this into my own code. Can anyone help me understand how and when you would use this kind of structure.
Thanks!
View all comments
1
u/Darwinmate Mar 20 '16
Never seen this before, searching around I've seen someone claim it's the same usage as C++ and assigning local variables (this doesn't seem right in R) and a few people saying anything in {} is faster... Here is an interesting blog: http://www.noamross.net/blog/2013/4/25/faster-talk.html
Can anyone confirm?