1

I am trying to create a function as follows:

LogVolLR <- function(x, y, z) {

  for (i in 2:nrow(x)) {

    x$y[i] <- (1 - 0.5) * x$y[i-1] + 3 + 8 * x$z[i]

  }
}

However I get an unknown or unitialised column error when I apply this function on a data frame. Please find an example below:

library(tidyverse)
set.seed(50)

df <- data_frame(SlNo = 1:2000,
                 Scenario = rep(c(1, 2, 3, 4),500),
                 A = round(rnorm(2000, 11, 6)),
                 B = round(rnorm(2000, 15, 4))) %>%
  arrange(Scenario) 

df<- df %>% split(f = .$Scenario) %>%
  map_dfr(~bind_rows(tibble(Scenario = 0), .x)) 

df <- df %>% mutate(C = if_else(Scenario != 0, 0, 4),
                    E = if_else(Scenario != 0, 0, 6))

LogVolLR(df, y = C, z = B)


> LogVolLR(df, y = C, z = B)

There were 50 or more warnings (use warnings() to see the first 50)

Warning messages:
1: Unknown or uninitialised column: 'y'.
2: Unknown or uninitialised column: 'y'.
3: Unknown or uninitialised column: 'z'.

I am not quite sure if I've coded my function correctly. Any help is greatly appreciated

zx8754
  • 52,746
  • 12
  • 114
  • 209
Dal
  • 317
  • 1
  • 8
  • 4
    You've got a few issues. When you pass `y = C` to your function, R will look for an object `C` in the global environment---you don't show a global definition for `C`, so that should throw an error immediately. The easy way to give a function a column is to use a string column name, `y = "C"`. But you can't use string column names with `$`, e.g., `mtcars$cyl` will *always* be the `cyl` column of `mtcars`, even if I set `cyl = "mpg"` or `cyl = "kkwwefsklfj"` first. So don't use `x$y` in your function, use `x[, y]` instead. Ditto for `z`. – Gregor Thomas Feb 13 '19 at 21:12
  • Not sure what your question has to do with `dplyr` or `tidyverse`, since you're using neither in your function or to call your function. Removing those tags. – Gregor Thomas Feb 13 '19 at 21:13
  • 2
    Tempted to close as duplicate of [Using `$` with a vector of column names](https://stackoverflow.com/q/18222286/903061) R-FAQ, as that's the root of the problem. – Gregor Thomas Feb 13 '19 at 21:15
  • However, if you *do* want to pass unquoted column names to your function, the `dplyr` vignette [Programming with `dplyr`](https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html) is a decent place to start. – Gregor Thomas Feb 13 '19 at 21:16

0 Answers0