Reputation: 401
I am trying to filter a column which contains a numeric/date name using a as.Date
variable.
As an example, consider this small database:
dt <- data.table(
names = c("A", "B", "C"),
`2020-01-01` = c(1, NA, 2),
`2020-01-02` = c(3, 4, 5),
`2020-01-03` = c(6, 7, 8)
)
I am currently filtering the desired date column as follows:
dt1 <- dt %>% filter(!is.na(`2020-01-01`)) %>% select(names)
My idea is to create a meeting_date
variable, this variable should be used as a date reference for all my R code.
meeting_date <- as.Date("2020-01-01")
But of course the code:
dt1 <- dt %>% filter(!is.na(meeting_date)) %>% select(names)
Does not work. The reason for this is the missing backticks, so without success I tried the following codes:
dt1 <- dt %>% filter(!is.na(paste("`", meeting_date, "`", sep=""))) %>% select(names)
dt1 <- dt %>% filter(!is.na(noquote(paste("`", meeting_date, "`", sep="")))) %>% select(names)
Does anyone knows how to proceed? Thanks!
Upvotes: 1
Views: 298
Reputation: 101753
You can use subset
+ is.na
as below
meeting_date <- "2020-01-01"
dtout <- subset(dt,as.vector(!is.na(dt[, ..meeting_date])))
such that
> dtout
names 2020-01-01 2020-01-02 2020-01-03
1: A 1 3 6
2: C 2 5 8
Upvotes: 0
Reputation: 5499
Long data should be easier to work with:
library(data.table)
dt <- data.table(
names = c("A", "B", "C"),
`2020-01-01` = c(1, NA, 2),
`2020-01-02` = c(3, 4, 5),
`2020-01-03` = c(6, 7, 8)
)
#Make data 'long' & change the new 'name' column to dates
# change confusing column 'name' to date while we're at it.
dt_long <- dt %>% pivot_longer(-names) %>%
mutate(date = lubridate::ymd(name)) %>%
select(-name)
meeting_date <- as.Date("2020-01-01")
dt_long %>% filter(date == meeting_date & (!is.na(value)))
Upvotes: 0
Reputation: 39858
You can do:
meeting_date <- as.Date("2020-01-01")
dt %>%
filter_at(vars(one_of(as.character(meeting_date))), ~ !is.na(.))
names 2020-01-01 2020-01-02 2020-01-03
1 A 1 3 6
2 C 2 5 8
Upvotes: 2