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

如何根据R中另一个数据帧的顺序排列数据帧?,r,dataframe,R,Dataframe,我有一个数据框记录不同位置的温度,另一个数据框记录观察温度数据的日期 比如说, temperature <- read.table(header=TRUE, text=' NewYork Boston Madison 32 22 7 27 13 28 15 0 5 ') date <- read.table(he

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

比如说,

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

如果添加行索引以维护行位置信息,并将数据帧重塑为长格式,则可以合并它们。使用
tidyr::gather
dplyr::internal\u join

库(tidyverse)
温度%rowid_到_列('i')%%>%聚集(城市,温度,-i)
)
#>加入,由=c(“i”、“城市”)
临时日期
#>#tibble:9 x 4
#>我是城市日期临时工
#>            
#>1纽约2013-08-09 32
#>2纽约2004-07-11 27
#>纽约2006-08-05 15
#>4 1波士顿2002-04-01 22
#>5 2波士顿2003-09-12 13
#>6 3波士顿2005-11-09 0
#>7 1麦迪逊2003-08-09 7
#>8.2麦迪逊2002-12-23 28
#>9 3麦迪逊2005-02-05 5

这里是一种使用
重塑2
的方法,该方法将每个城市的观测值与该城市记录的日期相匹配。结果是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

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

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

date[]谢谢。这正是我要找的。
> 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
> 
date[] <- Map(function(x, y) x[order(y)], date, temperature)