R-re形数据帧

R-re形数据帧,r,dataframe,group-by,R,Dataframe,Group By,我想在R中重新塑造我的数据帧。 以下是一个可重复生产的示例: ID <- c(1,1,1,2,2,2,3,3,3) type <- c("date","value","volume","date","value","volume","date","value","volume") value <- c("2020-01","100","1","2020-01","200","9","2020-02","100","3") df <- data.frame(ID, typ

我想在R中重新塑造我的数据帧。

以下是一个可重复生产的示例:

ID <- c(1,1,1,2,2,2,3,3,3)
type <- c("date","value","volume","date","value","volume","date","value","volume")
value <- c("2020-01","100","1","2020-01","200","9","2020-02","100","3")
df <- data.frame(ID, type, value)

ID这是一个从长到宽的转换

您可以使用
reformae2::melt
tidyr::pivot\u wide


ID这是一个从长到宽的转换

您可以使用
reformae2::melt
tidyr::pivot\u wide


ID
tidyverse
解决方案

library(tidyverse)
pivot_wider(df, id_cols = ID,names_from = type, values_from = value)

# A tibble: 3 x 4
     ID date    value volume
  <dbl> <fct>   <fct> <fct> 
1     1 2020-01 100   1     
2     2 2020-01 200   9     
3     3 2020-02 100   3 
库(tidyverse)
枢轴(df,id\u cols=id,name\u from=type,values\u from=value)
#一个tibble:3x4
ID日期值卷
1     1 2020-01 100   1     
2     2 2020-01 200   9     
3     3 2020-02 100   3 

tidyverse
解决方案

library(tidyverse)
pivot_wider(df, id_cols = ID,names_from = type, values_from = value)

# A tibble: 3 x 4
     ID date    value volume
  <dbl> <fct>   <fct> <fct> 
1     1 2020-01 100   1     
2     2 2020-01 200   9     
3     3 2020-02 100   3 
库(tidyverse)
枢轴(df,id\u cols=id,name\u from=type,values\u from=value)
#一个tibble:3x4
ID日期值卷
1     1 2020-01 100   1     
2     2 2020-01 200   9     
3     3 2020-02 100   3