rdata.tablesubsetsubtable

How to create a sub-table of another table with specific column entries in R?


I have the following table dT:

structure(list(delivDate = structure(c(20489, 20500, 20516, 20517, 
20518, 20533), class = "Date"), priceDate = structure(c(19724, 
19724, 19724, 19724, 19724, 19724), class = "Date"), priceIndex = c("KELAG HPFC DE", 
"HPFC DE", "HPFC DE", "HPFC DE", "HPFC DE", 
"HPFC DE"), avgPrice = c(109.65, 104.35, 104.5, 103.91, 
100.38, 76.57), quarters = c("Q1", "Q1", "Q1", "Q1", "Q1", "Q1"
)), row.names = c(NA, -6L), class = c("data.table", "data.frame"
))

Now, I have tried to create a new subset-table, which contains all columns of the origin table dT, but only these rows, which represents three specific priceDate-values.

I have tried the two following options, which both yield to an empty data table:

1) DT <- DT[priceDate %in% c("2024-01-02", "2024-03-05", "2024-03-12"), ]

2) base::subset(dT, (priceDate == '2024-01-02') & (priceDate == '2024-03-05') & (priceDate == '2024-03-12'))

Both yield to the following Error: Empty data.table (0 rows and 5 cols): delivDate,priceDate,priceIndex,avgPrice,quarters.

What am I doing wrong?


EDIT: This from a comment of @Soren works for my sample data:

dTNew <- dT[priceDate %in% as.Date(c("2024-01-02", "2024-03-05", "2024-03-12"))]

Solution

  • library(data.table)
    
    data <- structure(list(delivDate = structure(c(20489, 20500, 20516, 20517, 20518, 20533), class = "Date"),
                           priceDate = structure(c(19724, 19724, 19724, 19724, 19724, 19724), class = "Date"),
                           priceIndex = c("KELAG HPFC DE", "HPFC DE", "HPFC DE", "HPFC DE", "HPFC DE", "HPFC DE"),
                           avgPrice = c(109.65, 104.35, 104.5, 103.91, 100.38, 76.57),
                           quarters = c("Q1", "Q1", "Q1", "Q1", "Q1", "Q1")),
                      row.names = c(NA, -6L),
                      class = c("data.table", "data.frame"))
    
    specific_dates <- as.Date(c("2024-01-02", "2021-01-02", "2021-01-03"))
    subset_data <- data[priceDate %in% specific_dates]