2017-09-06 115 views
1

我需要更改给定数据帧(fruits.df)的索引值与另一个数据帧的日期(date.index)。替换一个数据帧的索引值与另一个数据帧的日期

实施例的数据:

# 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) 

这将产生以下日期帧:

enter image description here

的日期索引的数据帧的示例性数据:

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

所以我需要什么是以下内容:

enter image description here

我曾尝试使用TI的dplyr的过滤功能,但它的工作原理,只有当我明确地选择一列。

不起作用:

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

的作品,但我需要与整个DF做在同一时间:

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

回答

3

您可以在fruits.df的每一列使用match,即

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

其中给出,

 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> 
相关问题