Home > other >  Using both text and argument in same function in R
Using both text and argument in same function in R

Time:09-28

First of all need to create the same data;

library(tibbletime)
date <- seq(from = as.Date("1979-09-01"), to = as.Date("2019-12-01"), by = "month")
n <- length(date)
df <- matrix(NA, n, 2)
df <- data.frame(df)
var <- sample(1000:5000, n)
df[1] <- date
df[2] <- var
names(df) <- c("date", "var")
df <- as_tbl_time(df, index = date)

How can i use command below;

filter_time(df, ~"1979-09")

by paste0, eval(parse(text = "") I tried that one;

filter_time(eval(parse(text = paste0("df",",", "~" , "1979-09",sep = ""))))

but it didn't work. I have problem with time object which must be as text format. If that code works, it is possible to use in for loop, thanks.

CodePudding user response:

We could use reformulate to construct the expression

library(tibbletime)
filter_time(df, reformulate(termlabels = dQuote("1979-09", FALSE)))

-output

# A time tibble: 1 × 2
# Index: date
  date         var
  <date>     <int>
1 1979-09-01  1700

CodePudding user response:

You can also accomplish this with as.formula()

filter_time(df, as.formula(paste0("~", '"', year, '"')))

Full reprex:

library(tibbletime)

date <- seq(from = as.Date("1979-09-01"), to = as.Date("2019-12-01"), by = "month")
n <- length(date)
df <- matrix(NA, n, 2)
df <- data.frame(df)
var <- sample(1000:5000, n)
df[1] <- date
df[2] <- var
names(df) <- c("date", "var")
df <- as_tbl_time(df, index = date)

year <- paste("1979-09")
paste0("~", '"', year, '"')
#> [1] "~\"1979-09\""

as.formula(paste0("~", '"', year, '"'))
#> ~"1979-09"

filter_time(df, as.formula(paste0("~", '"', year, '"')))
#> # A time tibble: 1 x 2
#> # Index: date
#>   date         var
#>   <date>     <int>
#> 1 1979-09-01  3600
  • Related