首页 > 解决方案 > 如何在 R 中使用聚集而不是联合

问题描述

我正在尝试使用收集功能,而不是联合来获取输出。可以这样做吗?

这是我的数据:

 Description             Temp
     <fctr>                <dbl>

1   location1:48:2018-10-23 -0.9381736      
2   location2:83:2018-01-05 1.1714643       
3   location3:73:2018-11-05 -0.7064954      
4   location4:27:2018-07-26 0.4420571       
5   location5:33:2018-02-03 0.9060360       
6   location6:88:2018-04-27 1.9407284   

我曾经通过以下命令来分隔数据;

library(tidyr)
sepData <- separate(data, Description, c("Location",  "ID", "Date"), sep = ":")

Location ID   Date   Temp
<chr>   <chr> <chr>  <dbl>
1   location1   48  2018-10-23  -0.9381736
2   location2   83  2018-01-05  1.1714643
3   location3   73  2018-11-05  -0.7064954
4   location4   27  2018-07-26  0.4420571
5   location5   33  2018-02-03  0.9060360
6   location6   88  2018-04-27  1.9407284

现在我想使用收集将数据恢复为原始形式。如果可能,请提供帮助。

标签: r

解决方案


如果我们检查?separate,它还有一个remove默认的参数TRUE。将其更改为FALSE, 也将返回原始列而不将其从数据集中删除

separate(data, Description, c("Location",  "ID", "Date"), sep = ":", remove = FALSE)
#         Description  Location ID       Date       Temp
#1 location1:48:2018-10-23 location1 48 2018-10-23 -0.9381736
#2 location2:83:2018-01-05 location2 83 2018-01-05  1.1714643
#3 location3:73:2018-11-05 location3 73 2018-11-05 -0.7064954
#4 location4:27:2018-07-26 location4 27 2018-07-26  0.4420571
#5 location5:33:2018-02-03 location5 33 2018-02-03  0.9060360
#6 location6:88:2018-04-27 location6 88 2018-04-27  1.9407284

数据

data <- structure(list(Description = c("location1:48:2018-10-23", 
 "location2:83:2018-01-05", 
"location3:73:2018-11-05", "location4:27:2018-07-26", "location5:33:2018-02-03", 
"location6:88:2018-04-27"), Temp = c(-0.9381736, 1.1714643, -0.7064954, 
0.4420571, 0.906036, 1.9407284)), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6"))

推荐阅读