I'm writing a long script that takes a simple criterion to process meteorological data, such as counting the total days above 30 degrees per year, I just want to enter the criterion once, stored as an object, say:
var <- "V2 > 0"
to enter this at the top of the script; the problem is that when I pass it to
count(criterion = var)
it is being read as character and returns NaNs, i tried unquote(), as.name() which give no result, and as.factor() which gives a bad result, a sample of my data:
station = structure(list(V1 = structure(1:10, .Label = c("18/06/1982",
"19/06/1982", "20/06/1982", "21/06/1982", "22/06/1982", "23/06/1982",
"24/06/1982", "25/06/1982", "26/06/1982", "27/06/1982"), class = "factor"),
V2 = c(0, 0, 0, 0, 3.5, 2.2, 0, 0, 1, 1.1)), .Names = c("V1",
"V2"), row.names = c(NA, 10L), class = "data.frame")
the code i'm trying to run (by replacing V2 > 0 with the object var
):
library(dplyr)
library(lubridate)
station %>% mutate(V1=dmy(station$V1, tz="America/Mexico_City")) %>%
group_by(year(V1)) %>% count(criterion = V2 > 0 ) %>% filter(criterion == T) %>%
colMeans(na.rm = T)
You can use an expression and !!
:
cond = quo(V2 > 0)
station %>% mutate(V1=dmy(station$V1, tz="America/Mexico_City")) %>%
group_by(year(V1)) %>% count(criterion = !!cond ) %>% filter(criterion == T) %>%
colMeans(na.rm = T)
# year(V1) criterion n
# 1982 1 4