我们如何根据特定标准(例如日期)在 R 中排列两组数据
How do we arrange two sets of data according to a specific criteria, eg date, in R
这是关于 R 中的数据操作和清理。
我有数据集 1:
Date time Range Waterconsumption
1/1/01 0300 31km 2.0liters
2/1/01 0800 30km 1.8liters
3/1/01 0300 33km 1.7liters
4/1/01 0600 32km 1.8liters
5/1/01 0800 28km 1.7liters
6/1/01 0300 35km 1.6liters
7/1/01 0800 31km 1.8liters
还有数据集 2:
Date time heatlost weight
1/1/01 0300 0.27 61.5kg
2/1/01 0800 0.33 62.0kg
5/1/01 0800 0.69 61.7kg
6/1/01 0300 0.15 61.8kg
7/1/01 0800 0.63 62.0kg
如您所见,数据集 2 丢失了一些日期(从 3/1/01 到 4/1/01)。
那么我如何使用 cbind 组合数据集 1 和 2,即根据日期在耗水量 (dataset1) 后面插入热损失和重量?
您可以使用图书馆 dplyr::left_join(df1, df2, "time")
首先让我们生成一些数据以反映上面项目中的变量:
df1 <-
data.frame(
id = c(1:4),
time = c(1:4),
range = floor(runif(4, 28,32)),
watercon = round(runif(4,1.5,1.7),2)
)
df2 <-
data.frame(
id = c(1,4),
time = c(1,4),
heatlost = c(0.25,0.33),
weight = c(62.5,61.4)
)
根据您最初的问题,df2
有一些缺失值,当我们应用 left_join
时,这些值将被替换为 NA
。
如果您应用 left_join
加入 "time",然后使用 select
只保留您想要的变量:
library(dplyr)
left_join(df1, df2, "time") %>%
select(time, range, watercon, heatlost, weight)
您将获得返回的数据帧:
time range watercon heatlost weight
1 30 1.52 0.25 62.5
2 29 1.55 NA NA
3 29 1.51 NA NA
4 30 1.53 0.33 61.4
这是关于 R 中的数据操作和清理。
我有数据集 1:
Date time Range Waterconsumption
1/1/01 0300 31km 2.0liters
2/1/01 0800 30km 1.8liters
3/1/01 0300 33km 1.7liters
4/1/01 0600 32km 1.8liters
5/1/01 0800 28km 1.7liters
6/1/01 0300 35km 1.6liters
7/1/01 0800 31km 1.8liters
还有数据集 2:
Date time heatlost weight
1/1/01 0300 0.27 61.5kg
2/1/01 0800 0.33 62.0kg
5/1/01 0800 0.69 61.7kg
6/1/01 0300 0.15 61.8kg
7/1/01 0800 0.63 62.0kg
如您所见,数据集 2 丢失了一些日期(从 3/1/01 到 4/1/01)。
那么我如何使用 cbind 组合数据集 1 和 2,即根据日期在耗水量 (dataset1) 后面插入热损失和重量?
您可以使用图书馆 dplyr::left_join(df1, df2, "time")
首先让我们生成一些数据以反映上面项目中的变量:
df1 <-
data.frame(
id = c(1:4),
time = c(1:4),
range = floor(runif(4, 28,32)),
watercon = round(runif(4,1.5,1.7),2)
)
df2 <-
data.frame(
id = c(1,4),
time = c(1,4),
heatlost = c(0.25,0.33),
weight = c(62.5,61.4)
)
根据您最初的问题,df2
有一些缺失值,当我们应用 left_join
时,这些值将被替换为 NA
。
如果您应用 left_join
加入 "time",然后使用 select
只保留您想要的变量:
library(dplyr)
left_join(df1, df2, "time") %>%
select(time, range, watercon, heatlost, weight)
您将获得返回的数据帧:
time range watercon heatlost weight
1 30 1.52 0.25 62.5
2 29 1.55 NA NA
3 29 1.51 NA NA
4 30 1.53 0.33 61.4