Creating a pivot table

前端 未结 3 1953
情歌与酒
情歌与酒 2020-12-10 21:44

Suppose I have a dataset that looks like the following, in which years are listed down rows:

id<-c(1,1,1,2,2,2,3,3,3)
year<-c(1990, 1991, 1992, 1992, 1         


        
相关标签:
3条回答
  • 2020-12-10 22:09

    Another way to do it:

    > library(reshape2)
    > dcast(dataset, id ~ year, fill=0)
    # Using N as value column: use value.var to override.
      id 1990 1991 1992 1993 1994 1995
    1  1    7    8    9    0    0    0
    2  2    0    0    7    1    2    0
    3  3    0    0    0    5    4    3
    
    0 讨论(0)
  • 2020-12-10 22:09

    these days using tidyverse is more the rage:

    library(tidyr)
    
    dataset %>% 
      spread(year, N, fill = 0)
    
    0 讨论(0)
  • 2020-12-10 22:12
    > xtabs(N~id+year, data=dataset)
       year
    id  1990 1991 1992 1993 1994 1995
      1    7    8    9    0    0    0
      2    0    0    7    1    2    0
      3    0    0    0    5    4    3
    

    Your dataset is in "molten" form using the reshape2 terminology. Also known in data query circles as "first normal form".

    0 讨论(0)
提交回复
热议问题