0

Here is a simple function I wrote to help troubleshoot an issue. I have a function whose purpose is to return a tibble.

tstFunc <- function(n){
  n <- tibble(style = character(), color = character(), count =     integer())
  add_row(n, style = "old", color = "blue", count = 8)
  return(n)
}

When I execute this function:

tstFunc(b)

I get this response:

# A tibble: 0 x 3
# ... with 3 variables: style <chr>, color <chr>, count <int>

As you see, the row is NOT added to my tibble. However, when I execute this line at the console:

> testTibble <- tibble(style = character(), color = character(), count = integer())
> add_row(testTibble, style = "old", color = "blue", count = 8)
# A tibble: 1 x 3
  style color count
  <chr> <chr> <dbl>
1 old   blue      8

You see that the row HAS been added. What am I failing to grasp here? Thanks.

Charles Knell
  • 117
  • 1
  • 9
  • You have to assigned the results of `add_row` to something, just like everything else in R. Most functions do not operate via side effects. – joran Nov 28 '18 at 16:04
  • `add_row` returns a new value (which you are ignoring in your function) and you are just returning the original `n` value. If you just remove the `return(n)` line you would be returning the result of the `add_row` function. – MrFlick Nov 28 '18 at 16:04
  • Thank you both. A few minutes reflecting on joran's "side effect" remark made a light go on with respect to functional programming, and when I made a minor adjustment: `code` n<- add_row( ..., `code`, my problem was solved,. – Charles Knell Nov 28 '18 at 16:27

0 Answers0