I have built a function where I want to pass a data frame and a column from the data frame. For example:
testdf <- structure(list(date = c("2016-04-04", "2016-04-04", "2016-04-04",
"2016-04-04", "2016-04-04", "2016-04-04"), sensorheight = c(1L,
16L, 1L, 16L, 1L, 16L), farm = c("McDonald", "McDonald", "McDonald",
"McDonald", "McDonald", "McDonald"), location = c("4", "4", "5",
"5", "Outside", "Outside"), Temp = c(122.8875, 117.225, 102.0375,
98.3625, 88.5125, 94.7)), .Names = c("date", "sensorheight",
"farm", "location", "Temp"), row.names = c(NA, 6L), class = "data.frame")
> testdf
date sensorheight farm location Temp
1 2016-04-04 1 McDonald 4 122.8875
2 2016-04-04 16 McDonald 4 117.2250
3 2016-04-04 1 McDonald 5 102.0375
4 2016-04-04 16 McDonald 5 98.3625
5 2016-04-04 1 McDonald Outside 88.5125
6 2016-04-04 16 McDonald Outside 94.7000
The function subtracts some values from others based the values in different columns. It was working, accepting the data frame and column inputs, but since updating R, its not working.
DailyInOutDiff <- function (df, variable) {
DailyInOutDiff04 <- df %>%
filter(location %in% c(4, 'Outside')) %>%
group_by(date, sensorheight, farm) %>%
arrange(sensorheight, farm, location) %>%
summarise(Diff = if(n()==1) NA else variable[location=="4"] - variable[location=='Outside'],
location = "4") %>%
select(1, 2, 3, 5, 4)
DailyInOutDiff05 <- df %>%
filter(location %in% c(5, 'Outside')) %>%
group_by(date, sensorheight, farm) %>%
arrange(sensorheight, farm, location) %>%
summarise(Diff = if(n()==1) NA else variable[location=="5"] - variable[location=='Outside'],
location = "5") %>%
select(1, 2, 3, 5, 4)
temp.list <- list(DailyInOutDiff04, DailyInOutDiff05)
final.df = bind_rows(temp.list)
return(final.df)
}
test <- DailyInOutDiff(testdf, "Temp")
test <- DailyInOutDiff(testdf, quote(Temp))
They produce the following error messages:
Error in summarise_impl(.data, dots) :
Evaluation error: non-numeric argument to binary operator.
And
Error in summarise_impl(.data, dots) :
Evaluation error: object of type 'symbol' is not subsettable.
I would like to know the meaning of these error messages and how to address them.
I tried these solutions Pass a data.frame column name to a function, however none of the solutions worked for me.
The errors do not occur if I remove the column as an input, but I need the column because I am applying the function to multiple columns in a large data frame.
The output I would like:
date sensorheight farm location Temp
1 2016-04-04 1 McDonald 4 34.3750
2 2016-04-04 16 McDonald 4 22.5250
3 2016-04-04 1 McDonald 5 13.5250
4 2016-04-04 16 McDonald 5 3.6625