MHN
MHN

Reputation: 230

Replace index values of one data frame with dates of another data frame

I need to change the index values of a given data frame (fruits.df) with dates of another data frame (date.index).

Example Data:

# fruits.df    
x <- 1:5
y <- 1:12
z <- 1:16
w <- 1:7
fruits.list <- list(Apples = x, Bananas = y, Grapes = z, Kiwis = w)

library(qpcR)
fruits.df <- do.call(qpcR:::cbind.na, lapply(
   fruits.list, data.frame))

names(fruits.df) <- names(fruits.list)

This produces the following date frame:

enter image description here

Example data for the date index data frame:

date.index <- data.frame(Days = seq(as.Date("2017-07-01"), 
  as.Date("2017-07-20"), by = 1), index = as.integer(1:20))

So what I need is the following:

enter image description here

I have tried ti use the filter function of dplyr but it works only when I explicitly select a column.

Does not work:

filtered_found_Index <- filter(date.index, index %in% 
    fruits.df)

Works, but I need to do it at the same time with the whole df:

filtered_found_Index <- filter(date.index, index %in% 
    fruits.df$**Bananas**)

Upvotes: 1

Views: 355

Answers (1)

Sotos
Sotos

Reputation: 51592

You can use match on each column of your fruits.df, i.e.

fruits.df[] <- lapply(fruits.df, function(i) date.index$Days[match(i, date.index$index)])

which gives,

       Apples    Bananas     Grapes      Kiwis
1  2017-07-01 2017-07-01 2017-07-01 2017-07-01
2  2017-07-02 2017-07-02 2017-07-02 2017-07-02
3  2017-07-03 2017-07-03 2017-07-03 2017-07-03
4  2017-07-04 2017-07-04 2017-07-04 2017-07-04
5  2017-07-05 2017-07-05 2017-07-05 2017-07-05
6        <NA> 2017-07-06 2017-07-06 2017-07-06
7        <NA> 2017-07-07 2017-07-07 2017-07-07
8        <NA> 2017-07-08 2017-07-08       <NA>
9        <NA> 2017-07-09 2017-07-09       <NA>
10       <NA> 2017-07-10 2017-07-10       <NA>
11       <NA> 2017-07-11 2017-07-11       <NA>
12       <NA> 2017-07-12 2017-07-12       <NA>
13       <NA>       <NA> 2017-07-13       <NA>
14       <NA>       <NA> 2017-07-14       <NA>
15       <NA>       <NA> 2017-07-15       <NA>
16       <NA>       <NA> 2017-07-16       <NA>

Upvotes: 3

Related Questions