2

Let the data be:

> dput(df)
structure(list(NAME.x = c("ANNE", "BOB", "CATHY", "DIANNE", "EMILY"
), NAME.y = c(NA, "BOB", "CATHY", "DIANNE", NA), AGE.x = c("81", 
"47", "47", "47", "37"), AGE.y = c(NA, "47", "47", "47", NA), 
    ADMISSIONDATE.x = structure(c(1380751296, 1382088000, 1382088000, 
    1382088000, 1383207720), class = c("POSIXct", "POSIXt"), tzone = "UTC"), 
    ADMISSIONDATE.y = structure(c(NA, 1382088000, 1382088000, 
    1382088000, NA), class = c("POSIXct", "POSIXt"), tzone = "UTC"), 
    DISCHARGEDDATE.x = structure(c(1381172735, 1382189165, 1382189165, 
    1382189165, 1383250549), class = c("POSIXct", "POSIXt"), tzone = "UTC"), 
    DISCHARGEDDATE.y = structure(c(NA, 1382189165, 1382189165, 
    1382189165, NA), class = c("POSIXct", "POSIXt"), tzone = "UTC")), row.names = c(NA, 
-5L), .Names = c("NAME.x", "NAME.y", "AGE.x", "AGE.y", "ADMISSIONDATE.x", 
"ADMISSIONDATE.y", "DISCHARGEDDATE.x", "DISCHARGEDDATE.y"), class = "data.frame")

I would like to check the similarity and the difference between common variables in this dataset. I tried to write a function, where the 3 arguments are the dataset, and the 2 variables in the dataset.

  check<-function(data,var1,var2){
    # X1: x and y are equal
    # X2: x and y are not equal
    # Y1: x and y are non-empty
    # Y2: x and y are empty
    # Z1: x is non-empty and y is empty
    # Z2: x is empty and y is non-empty
    cnt_each<-data %>% 
      mutate(X1 = (var1==var2),
             X2 = (var1!=var2),
             Y1 = (!is.na(var1) & !is.na(var2)),
             Y2 = (is.na(var1) & is.na(var2)),
             Z1 = (!is.na(var1) & is.na(var2)),
             Z2 = (is.na(var1) & !is.na(var2))) %>%
      summarise_at("X1:Z2",funs(sum(.))) %>%
      mutate(sum_all=sum(.,na.rm=TRUE))
    return(cnt_each)
  }

However, it gives an error when being run. There is no error when I run the code outside the function.

check(df,NAME.x,NAME.y)

Error in mutate_impl(.data, dots) : object 'NAME.x' not found

HNSKD
  • 1,614
  • 2
  • 14
  • 25

1 Answers1

2

We can make use of the devel version of dplyr (soon to be released 0.6.0 for doing this). The enquo takes the input arguments and converts to quosure. Within the mutate/summarise/group_by, the quosures are unquoted (!! or UQ) for evaluation

check<-function(data,var1,var2){
  var1 <- enquo(var1)
  var2 <- enquo(var2) 
  data %>%
       mutate(X1 = UQ(var1)==UQ(var2),
              X2 = UQ(var1) != UQ(var2),
              Y1 = !is.na(UQ(var1)) &  !is.na(UQ(var2)),
              Y2 = is.na(UQ(var1)) & is.na(UQ(var2)),
              Z1 = !is.na(UQ(var1)) & !is.na(UQ(var2)),
              Z2 = is.na(UQ(var1)) & !is.na(UQ(var2))) %>%
        summarise_at(vars(X1:Z2), funs(sum(., na.rm = TRUE))) %>%
        mutate(sum_all = rowSums(., na.rm = TRUE))

}    


check(df, NAME.x, NAME.y)
#   X1 X2 Y1 Y2 Z1 Z2 sum_all
#1  3  0  3  0  3  0       9
akrun
  • 874,273
  • 37
  • 540
  • 662