Creating variables from factor records in R

前端 未结 2 1438
感动是毒
感动是毒 2021-01-07 12:10

I am kind of lost, I have a data frame that looks like this:

tract   ageClass    count
    1      [0-4]       71
    2      [0-4]      192
    3      [0-4]           


        
相关标签:
2条回答
  • 2021-01-07 12:42

    Three possible options I can think of (assuming your data set called df)

    xtabs(count ~ tract + ageClass, df) 
    #       ageClass
    # tract [0-4] [5-8]
    #     1    71     9
    #     2   192    86
    #     3    81    42
    

    Or

    library(reshape2)
    dcast(df, tract ~ ageClass, value.var = "count") 
    #   tract [0-4] [5-8]
    # 1     1    71     9
    # 2     2   192    86
    # 3     3    81    42
    

    Or

    library(tidyr)
    spread(df, ageClass, count)
    #   tract [0-4] [5-8]
    # 1     1    71     9
    # 2     2   192    86
    # 3     3    81    42
    
    0 讨论(0)
  • 2021-01-07 12:54
    ageClass <- c("[0-4]", "[5-8]")
    ageClassDF <- lapply(ageClass, function(x) dx[which(dx$ageClass==x), ])
    
    ageClassDF <- Reduce(function(...) merge(..., by = "tract.1", all = TRUE), ageClassDF )
    
    0 讨论(0)
提交回复
热议问题