r-透视/重塑和创建新列



我的数据帧

City   Ind: Money    Position Money    Ind: Health   Position Health 
NY       6             5                   4          3
LA       2             1                   9          8
BA       7             11                 13          15

所需数据帧

Ind   Position_NY  Position_LA  Position_BA   Ind_NY  Ind_LA Ind_BA   
Money      5          1            11           6       2        7
Health     3          8            15           4       9        13

谢谢

这对您有帮助吗?

library(tidyverse)
df <- tribble(
~City, ~`Ind: Money`,    ~`Position Money`,    ~`Ind: Health`,   ~`Position Health` ,
"NY", 6, 5, 4, 3,
"LA", 2, 1 , 9, 8,
"BA", 7, 11, 13, 15
)
data <- pivot_longer(df, cols = starts_with(c("Ind", "Position"))) %>% 
separate(name, c("var", "Ind")) %>% 
pivot_wider(names_from = c("City", "var"))

相关内容

  • 没有找到相关文章

最新更新