2014-10-20 133 views
0

我有一个像重新安排数据帧

col1 col2 col3 col4 
    a  0  t  .1 
    b  0  t  .2 
    a  1  f  .3 
    b  1  f  .4 

数据帧我需要重新安排它这种格式

  a  b 
0 t .1 .2 
1 f .3 .4 

我知道这可以用dcast函数来完成。但我无法弄清楚究竟是如何?

回答

2

正如你提到的,这可以用dcast从 “reshape2” 完成:

library(reshape2) 
dcast(mydf, col2 + col3 ~ col1, value.var = "col4") 
# col2 col3 a b 
# 1 0 t 0.1 0.2 
# 2 1 f 0.3 0.4 

它也可以与reshape从基础R做:

> reshape(mydf, direction = "wide", idvar = c("col2", "col3"), timevar = "col1") 
    col2 col3 col4.a col4.b 
1 0 t 0.1 0.2 
3 1 f 0.3 0.4 

而且随着spread ,来自“tidyr”:

> library(dplyr) 
> library(tidyr) 
> mydf %>% spread(col1, col4) 
    col2 col3 a b 
1 0 t 0.1 0.2 
2 1 f 0.3 0.4 
+0

如果我必须按降序排列每行中的a和b的所有值,该怎么办? – user3664020 2014-10-20 06:39:10

+1

@ user3664020 - 先对原始数据中的值进行排序,然后重新整形。 – thelatemail 2014-10-20 06:46:18