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