R 数据从长到宽,具有多个输出 columns/values
R data long to wide with multiple output columns/values
苦苦思索如何措辞,所以我无法通过搜索找到很好的结果。输入示例:
cust_id make part price color
1 jeep wheel 10 gray
1 jeep door 5 blue
1 jeep seat 20 brown
2 ford wheel 12 gray
2 ford door 8 red
2 ford seat 25 brown
期望的输出:
cust_ID make wheel_price wheel_color door_price door_color seat_price seat_color
1 jeep 10 gray 5 blue 20 brown
2 ford 12 gray 8 red 25 brown
最初是使用 spread() 但 运行 遇到字符串值问题。切换到 pivot_wider() 但仍然无法为每个唯一部分获得多个输出 columns/values。提前致谢!
你必须使用 pivot_wider:
library(dplyr)
library(tidyr)
df %>%
tidyr::pivot_wider(names_from = part, names_glue = "{part}_{.value}", values_from = c(price, color)) %>%
dplyr::select(1, 2, sort(current_vars()))
cust_id make door_color door_price seat_color seat_price wheel_color wheel_price
<int> <chr> <chr> <int> <chr> <int> <chr> <int>
1 1 jeep blue 5 brown 20 gray 10
2 2 ford red 8 brown 25 gray 12
苦苦思索如何措辞,所以我无法通过搜索找到很好的结果。输入示例:
cust_id make part price color
1 jeep wheel 10 gray
1 jeep door 5 blue
1 jeep seat 20 brown
2 ford wheel 12 gray
2 ford door 8 red
2 ford seat 25 brown
期望的输出:
cust_ID make wheel_price wheel_color door_price door_color seat_price seat_color
1 jeep 10 gray 5 blue 20 brown
2 ford 12 gray 8 red 25 brown
最初是使用 spread() 但 运行 遇到字符串值问题。切换到 pivot_wider() 但仍然无法为每个唯一部分获得多个输出 columns/values。提前致谢!
你必须使用 pivot_wider:
library(dplyr)
library(tidyr)
df %>%
tidyr::pivot_wider(names_from = part, names_glue = "{part}_{.value}", values_from = c(price, color)) %>%
dplyr::select(1, 2, sort(current_vars()))
cust_id make door_color door_price seat_color seat_price wheel_color wheel_price
<int> <chr> <chr> <int> <chr> <int> <chr> <int>
1 1 jeep blue 5 brown 20 gray 10
2 2 ford red 8 brown 25 gray 12