r - 在 R 中的两列上使用 pivot_wide() 从长转换为宽
问题描述
我想通过两列中的值将我的数据从长格式转换为宽格式。我怎样才能做到这一点tidyverse
?
更新dput
structure(list(Country = c("Algeria", "Benin", "Ghana", "Algeria",
"Benin", "Ghana", "Algeria", "Benin", "Ghana"
), Indicator = c("Indicator 1",
"Indicator 1",
"Indicator 1",
"Indicator 2",
"Indicator 2",
"Indicator 2",
"Indicator 3",
"Indicator 3",
"Indicator 3"
), Status = c("Actual", "Forecast", "Target", "Actual", "Forecast",
"Target", "Actual", "Forecast", "Target"), Value = c(34, 15, 5,
28, 5, 2, 43, 5,
1)), row.names
= c(NA, -9L), class = c("tbl_df", "tbl", "data.frame"))
Country Indicator Status Value
<chr> <chr> <chr> <dbl>
1 Algeria Indicator 1 Actual 34
2 Benin Indicator 1 Forecast 15
3 Ghana Indicator 1 Target 5
4 Algeria Indicator 2 Actual 28
5 Benin Indicator 2 Forecast 5
6 Ghana Indicator 2 Target 2
7 Algeria Indicator 3 Actual 43
8 Benin Indicator 3 Forecast 5
9 Ghana Indicator 3 Target 1
预期产出
Country Indicator1_Actual Indicator1_Forecast Indicator1_Target Indicator2_Actual
Algeria 34 15 5 28
ETC
感谢任何提示!
foo <- data %>% pivot_wider(names_from = c("Indicator","Status"), values_from = "Value")
完美运行!
解决方案
我认为错误在于您的pivot_wider()
命令
data %>% pivot_wider(names_from = Indicator, values_from = c(Indicator, Status))
我敢打赌,您不能将同一列用于名称和值。
试试这个代码
data %>% pivot_wider(names_from = c(Indicator, Status), values_from = Value))
说明:由于您希望列名称为Indicator 1_Actual,因此您需要将列指示符和状态都输入到您的names_from
如果您提供示例数据和预期输出,将会很有帮助。但是我在我的虚拟数据上对此进行了测试,它给出了预期的输出 -
数据:
# A tibble: 4 x 4
a1 a2 a3 a4
<int> <int> <chr> <dbl>
1 1 5 s 10
2 2 4 s 20
3 3 3 n 30
4 4 2 n 40
称呼 :a %>% pivot_wider(names_from = c(a2, a3), values_from = a4)
输出 :
# A tibble: 4 x 5
a1 `5_s` `4_s` `3_n` `2_n`
<int> <dbl> <dbl> <dbl> <dbl>
1 1 10 NA NA NA
2 2 NA 20 NA NA
3 3 NA NA 30 NA
4 4 NA NA NA 40
如果要复制,请在此处提供数据
structure(list(a1 = 1:4, a2 = 5:2, a3 = c("s", "s", "n", "n"),
a4 = c(10, 20, 30, 40)), row.names = c(NA, -4L), class = c("tbl_df",
"tbl", "data.frame"))
编辑:对于尝试正确pivot_wider()
命令后编辑的问题-看起来您的数据实际上可能有重复项,在这种情况下,您看到的输出将是有意义的-我建议您尝试通过以下方式确定您的数据是否确实有重复项使用filter(Country == .., Indicator == .., Status == ..)
推荐阅读
- javascript - 为什么会自动循环?
- c - 在为副本转换后,我是否需要再次为算术转换 void 指针?
- mqtt - 如何通过 custom_mqtt_uplink_converter 在 Thingsboard IoT Gateway 中使用 deviceNameTopicExpression?
- html - Emailer - 将 html 源代码嵌入到电子邮件中
- testing - 如何从导出到 JSON 的 POSTMAN 集合中获取 KARATE fatures
- hadoop - HDFS 集群中的 HDFS 副本 + 和最小数据节点数
- javascript - 元素拖入反应
- python - 图像更新抛出 generic.UpdateView 不工作
- http - 在 http.Handler 中确定 HTTP 请求的 IP 地址
- laravel - 合并由 browser-kit-testing 测试的 laravel 代码的代码覆盖率的奇怪行为