Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在R中将行转换为多列_R_Transpose - Fatal编程技术网

在R中将行转换为多列

在R中将行转换为多列,r,transpose,R,Transpose,我有以下数据帧df ID Year Var value 1 2011 x1 1.2 1 2011 x2 2 1 2012 x1 1.5 1 2012 x2 2.3 3 2013 x1 3 3 2014 x1 4 4 2015 x1 5 5 2016 x1 6 4 2016 x1 2 我想用以下格式转换数据 ID Year x1 x2 1 2011 1.2 2 1 2011 2 NA 1 2012 1.5 2.3 3

我有以下数据帧df

ID Year Var value
1  2011  x1  1.2
1  2011  x2  2
1  2012  x1  1.5
1  2012  x2  2.3
3  2013  x1  3
3  2014  x1  4
4  2015  x1  5
5  2016  x1  6
4  2016  x1  2
我想用以下格式转换数据

ID Year  x1  x2 
1  2011  1.2 2
1  2011  2   NA  
1  2012  1.5 2.3
3  2013  3   NA
3  2014  4   4
4  2015  5   NA
4  2016  2   NA
5  2016  6   NA

请使用
tidyr
库提供帮助,我相信这就是您要寻找的:

df <- data.frame(stringsAsFactors=FALSE,
          ID = c(1L, 1L, 1L, 1L, 3L, 3L, 4L, 5L, 4L),
        Year = c(2011L, 2011L, 2012L, 2012L, 2013L, 2014L, 2015L, 2016L, 2016L),
         Var = c("x1", "x2", "x1", "x2", "x1", "x1", "x1", "x1", "x1"),
       value = c(1.2, 2, 1.5, 2.3, 3, 4, 5, 6, 2)
)

library(tidyr)

df2 <- df %>% 
  spread(Var, value)
df可能重复的