Skip to content

spread with missing values of a factor of key_value #25

@MCOtto

Description

@MCOtto

I want to make tables from different data where I use spread to make tables with levels of a factor for columns. spread is a good tool to do this. I need all columns even if there are no observations of some levels of the factor. reshape::cast with add.missing accomplished this; spread has no option with the same ability. Here is a simple example:

require(tidyr)
 require(dplyr)
 Data<-expand.grid(
    row=paste("r",1:3,sep=""),
    col=paste("c",1:4,sep="")   
 )

 Data<-mutate(Data,
    value=as.integer(gsub("[rc]","",paste(row,col,sep="")))
 )

 filter(Data,col!="c3")%>%
 spread(col,value,fill=0)

 require(reshape)
 filter(Data,col!="c3")%>%
 cast(row~col,
  add.missing=TRUE,value="value",fill=0
 )

cast keeps c3 even though there are not values because levels(Data$col) has all the columns. Spread does not:

row c1 c2 c3 c4
1 r1 11 12 0 14
2 r2 21 22 0 24
3 r3 31 32 0 34

This is the facility from cast I would like retained or returned. May be I am missing something in the spread options or some other function I should be using in tid- or dpl-yr.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions