How would I go about using mutate
(my presumption is that I am looking for standard evaluation in my case, and hence mutate_
, but I am not entirely confident on this point) when using a function that accepts a list of variable names, such as this:
createSum = function(data, variableNames) {
data %>%
mutate_(sumvar = interp(~ sum(var, na.rm = TRUE),
var = as.name(paste(as.character(variableNames), collapse =","))))
}
Here is an MWE that strips the function to its core logic and demonstrates what I am trying to achieve:
library(dplyr)
library(lazyeval)
# function to make random table with given column names
makeTable = function(colNames, sampleSize) {
liSample = lapply(colNames, function(week) {
sample = rnorm(sampleSize)
})
names(liSample) = as.character(colNames)
return(tbl_df(data.frame(liSample, check.names = FALSE)))
}
# create some sample data with the column name patterns required
weekDates = seq.Date(from = as.Date("2014-01-01"),
to = as.Date("2014-08-01"), by = "week")
dfTest = makeTable(weekDates, 10)
# test mutate on this table
dfTest %>%
mutate_(sumvar = interp(~ sum(var, na.rm = TRUE),
var = as.name(paste(as.character(weekDates), collapse =","))))
Expected output here is what would be returned by:
rowSums(dfTest[, as.character(weekDates)])
makeTable
but then callmakeDataFrame
. Are these supposed to be the same function? It would be helpful to describe the output you expect for this sample input (set a seed to the data is reproducible). – MrFlicksum
of all the variables whose variable names are passes to the function, by row. Will update with expected output. – tchakravarty