将行转换为 R 中数据框的列
Converting rows to columns for a dataframe in R
我有如下数据框。
Date Time Object_Name Object_Value
7/28/2017 8:00 A1 58.56
7/28/2017 8:00 A2 51.66
.
.
.
7/28/2017 8:30 A1 60.2
7/28/2017 8:30 A2 65.2
我需要这样改造:
Date Time A1 A2
7/28/2017 8:00 58.5 51.6
7/28/2017 8:30 60.2 65.2
尝试
library(reshape2)
df
Date Time Object_Name Object_Value
1 7/28/2017 8:00 A1 58.56
2 7/28/2017 8:00 A2 51.66
3 7/28/2017 8:30 A1 60.20
4 7/28/2017 8:30 A2 65.20
dcast(df, Date + Time ~ Object_Name)
Date Time A1 A2
1 7/28/2017 8:00 58.56 51.66
2 7/28/2017 8:30 60.20 65.20
或者,
library(tidyr)
spread(df, Object_Name, Object_Value)
Date Time A1 A2
1 7/28/2017 8:00 58.56 51.66
2 7/28/2017 8:30 60.20 65.20
为了解决评论,如果您有特殊情况,以上方法很有效。例如考虑以下内容:
df
Date Time Object_Name Object_Value
1 7/28/2017 8:00 A1 58.56
2 7/28/2017 8:00 A1 50.00
3 7/28/2017 8:00 A2 51.66
4 7/28/2017 8:30 A1 60.20
5 7/28/2017 8:30 A2 65.20
查看前两行,您可以看到对于相同的日期、时间和 Object_Name,我们有两个值。这意味着 dcast
不知道该怎么做并发出以下警告:Aggregation function missing: defaulting to length
。我们可以通过指定聚合函数来处理这个问题。例如,让我们取这些值的平均值:
dcast(df, Date + Time ~ Object_Name, fun.aggregate = mean)
Date Time A1 A2
1 7/28/2017 8:00 54.28 51.66
2 7/28/2017 8:30 60.20 65.20
我有如下数据框。
Date Time Object_Name Object_Value
7/28/2017 8:00 A1 58.56
7/28/2017 8:00 A2 51.66
.
.
.
7/28/2017 8:30 A1 60.2
7/28/2017 8:30 A2 65.2
我需要这样改造:
Date Time A1 A2
7/28/2017 8:00 58.5 51.6
7/28/2017 8:30 60.2 65.2
尝试
library(reshape2)
df
Date Time Object_Name Object_Value
1 7/28/2017 8:00 A1 58.56
2 7/28/2017 8:00 A2 51.66
3 7/28/2017 8:30 A1 60.20
4 7/28/2017 8:30 A2 65.20
dcast(df, Date + Time ~ Object_Name)
Date Time A1 A2
1 7/28/2017 8:00 58.56 51.66
2 7/28/2017 8:30 60.20 65.20
或者,
library(tidyr)
spread(df, Object_Name, Object_Value)
Date Time A1 A2
1 7/28/2017 8:00 58.56 51.66
2 7/28/2017 8:30 60.20 65.20
为了解决评论,如果您有特殊情况,以上方法很有效。例如考虑以下内容:
df
Date Time Object_Name Object_Value
1 7/28/2017 8:00 A1 58.56
2 7/28/2017 8:00 A1 50.00
3 7/28/2017 8:00 A2 51.66
4 7/28/2017 8:30 A1 60.20
5 7/28/2017 8:30 A2 65.20
查看前两行,您可以看到对于相同的日期、时间和 Object_Name,我们有两个值。这意味着 dcast
不知道该怎么做并发出以下警告:Aggregation function missing: defaulting to length
。我们可以通过指定聚合函数来处理这个问题。例如,让我们取这些值的平均值:
dcast(df, Date + Time ~ Object_Name, fun.aggregate = mean)
Date Time A1 A2
1 7/28/2017 8:00 54.28 51.66
2 7/28/2017 8:30 60.20 65.20