3
votes

I am trying to set up a function in R which prepares data in a specific format to be fed into a correlogram. When manipulating datasets I tend to use dplyr due to its clarity and ease of use, but I am running into problems trying to pass a dataset and specified column names into this function while using dplyr.

This is the set up, included here (in slightly abbreviated form) for clarity. I have not encountered any errors with this and before posting this I confirmed corrData is set up properly:

library(corrplot)
library(tidyverse)
library(stringr)

table2a <- table2 %>%
    mutate(example_index = str_c(country,year, sep="."))

Here is the actual function:

prepCorr <- function(dtable, x2, index2) { 

  practice <- dtable %>%
    select(index2, x2) %>%
    mutate(count=1) %>%
    complete(index2, x2)

  practice$count[is.na(practice$count)] <- 0

  practice <- spread(practice, key = x2, value = count)

  M <- cor(practice)
  return(M)
}

prepCorr(table2a, type, example_index)

Whenever I run this function I get:

Error in overscope_eval_next(overscope, expr) : object 'example_index' not found

I have also tried to take advantage of quosures to fix this, but recieve a different error when I do so. When I run the following modified code:

prepCorr <- function(dtable, x2, index2) { 
  x2 <- enquo(x2)
  index2 <- enquo(index2)

  practice <- dtable %>%
    select(!!index2, !!x2) %>%
    mutate(count=1) %>%
    complete(!!index2, !!x2)

  practice$count[is.na(practice$count)] <- 0

  practice <- spread(practice, key = !!x2, value = count)

  return(cor(practice))
}

prepCorr(table2a, type, example_index)

I get:

Error in !index2 : invalid argument type 

What am I doing wrong here, and how can I fix this? I believe I am using dplyr 0.7 for clarification.

UPDATE: replaced old example with reproducible example.

1
Can you post a reproducible example?csgroen
Would it be alright if I edited the question to use table2 from the tidyverse package rather than the tables shown here? It should work for this purpose nicely.Josh Kraushaar
Sure, as long as it gives the same error and we can use it to "debug"csgroen
Ok, it should be reproducible now, thank you for the pointer.Josh Kraushaar
Save the RStudio for RStudio-speific problems. (The RStudio interface, or code that works in RGui or on the R command line, but not in RStudio.)Gregor Thomas

1 Answers

2
votes

Look at this example

library(dplyr)
myfun <- function(df, col1, col2) {
              col1 <- enquo(col1)     # need to quote
              col2 <- enquo(col2)
              df1 <- df %>%
                       select(!!col1, !!col2)   #!! unquotes
              return(df1)
         }

myfun(mtcars, cyl, gear)

You can learn more here link about NSE vs SE