如何根据R中另一个数据帧的顺序排列数据帧?

时间:2017-12-17 00:12:38

标签: r dataframe

我有一个数据帧记录不同位置的温度,另一个数据帧记录观察温度数据的日期。

例如,

temperature <- read.table(header=TRUE, text='
               NewYork Boston   Madison
                  32     22  7
                  27     13  28
                  15     0 5 ')


date <- read.table(header=TRUE, text='
        NewYork          Boston      Madison
        2013-08-09     2002-04-01  2003-08-09
        2004-07-11     2003-09-12  2002-12-23
        2006-08-05     2005-11-09  2005-02-05 ')

我使用“apply”函数来获取温度数据的顺序,但是如何根据我得到的顺序排列日期数据。

apply(temperature, 2, order)

3 个答案:

答案 0 :(得分:1)

我们可以使用Map从另一个数据集中的order对一个数据集的相应列进行排序

date[] <- Map(function(x, y) x[order(y)], date, temperature)

答案 1 :(得分:0)

如果添加行索引以维护行位置信息并将数据帧重新整形为长格式,则可以加入它们。使用tidyr::gatherdplyr::inner_join

library(tidyverse)

temperature <- read_table(
'NewYork   Boston   Madison
      32       22         7
      27       13        28
      15        0         5')

date <- read_table(
  'NewYork         Boston     Madison
2013-08-09     2002-04-01  2003-08-09
2004-07-11     2003-09-12  2002-12-23
2006-08-05     2005-11-09  2005-02-05')

temp_date <- inner_join(
    date %>% rowid_to_column('i') %>% gather(city, date, -i),
    temperature %>% rowid_to_column('i') %>% gather(city, temp, -i)
)
#> Joining, by = c("i", "city")

temp_date
#> # A tibble: 9 x 4
#>       i    city       date  temp
#>   <int>   <chr>     <date> <int>
#> 1     1 NewYork 2013-08-09    32
#> 2     2 NewYork 2004-07-11    27
#> 3     3 NewYork 2006-08-05    15
#> 4     1  Boston 2002-04-01    22
#> 5     2  Boston 2003-09-12    13
#> 6     3  Boston 2005-11-09     0
#> 7     1 Madison 2003-08-09     7
#> 8     2 Madison 2002-12-23    28
#> 9     3 Madison 2005-02-05     5

答案 2 :(得分:0)

这是一种使用reshape2的方法,该方法与每个城市的观察结果相匹配,并记录该城市的日期。结果是9行数据,除了温度值之外还有城市名称和日期列。

temperature <- read.table(header = TRUE, text = '
               NewYork Boston   Madison
                          32     22  7
                          27     13  28
                          15     0 5 ')

date <- read.table(header = TRUE, text = '
                   NewYork          Boston      Madison
                   2013-08-09     2002-04-01  2003-08-09
                   2004-07-11     2003-09-12  2002-12-23
                   2006-08-05     2005-11-09  2005-02-05 ')

library(reshape2)

meltTemp <- melt(temperature)
meltTemp$date <- melt(date,measure.vars=c("NewYork","Boston","Madison"))[,"value"]
meltTemp

...和输出。

> meltTemp
  variable value       date
1  NewYork    32 2013-08-09
2  NewYork    27 2004-07-11
3  NewYork    15 2006-08-05
4   Boston    22 2002-04-01
5   Boston    13 2003-09-12
6   Boston     0 2005-11-09
7  Madison     7 2003-08-09
8  Madison    28 2002-12-23
9  Madison     5 2005-02-05
> 
相关问题