Home > Blockchain >  R: Manually Specifying Factor Levels
R: Manually Specifying Factor Levels

Time:01-24

I am working with the R programming language.

Suppose I have the following data set:

v1 <- c("2010-01","2010-02", "2010-03", "2010-04", "2010-05") 
v2 <- c("A", "B", "C", "D", "E")


dates <- as.factor(sample(v1, 1000, replace=TRUE, prob=c(0.5, 0.2, 0.1, 0.1, 0.1)))

types <- as.factor(sample(v2,1000, replace=TRUE, prob=c(0.3, 0.2, 0.1, 0.1, 0.1)))

var = rnorm(1000,10,10)

problem_data = data.frame(var,dates, types)

> head(problem_data)

        var   dates types
1 -6.772497 2010-01     A
2  6.769367 2010-01     D
3 18.914358 2010-02     C
4  6.517997 2010-02     E
5 19.616047 2010-01     B
6  5.129928 2010-01     B

I am trying to make a final data set that contains a new column for each unique "group" within the "types" column.

I found out how to do this using the "xtabs" statement in R:

library(dplyr)

graph_data = data.frame(problem_data %>% group_by(dates, types) %>% summarise(count = n()))

   graph_data$types <- factor(graph_data$types, levels = c("A", "B", "C", "D", "E"))
    
    final = data.frame(xtabs(count ~ dates   types, graph_data))
    
        dates types Freq
1 2010-01     A  161
2 2010-02     A   76
3 2010-03     A   42
4 2010-04     A   45
5 2010-05     A   46
6 2010-01     B  132

My Question: Is it possible to do this without manually specifying the factor levels?

I thought of the following way to do this:

graph_data$types <- factor(graph_data$types, levels = levels(problem_data$types))

Is this the correct way to do this? Are there any other ways of doing this?

Thanks!

CodePudding user response:

Is this helpful?

library(dplyr)

problem_data %>%
  group_by(types) %>%
  count(dates)
#> # A tibble: 25 × 3
#> # Groups:   types [5]
#>    types dates       n
#>    <fct> <fct>   <int>
#>  1 A     2010-01   188
#>  2 A     2010-02    77
#>  3 A     2010-03    35
#>  4 A     2010-04    32
#>  5 A     2010-05    31
#>  6 B     2010-01   137
#>  7 B     2010-02    64
#>  8 B     2010-03    27
#>  9 B     2010-04    28
#> 10 B     2010-05    20
#> # … with 15 more rows

Created on 2022-01-23 by the reprex package (v2.0.1)

data:

set.seed(111)
v1 <- c("2010-01", "2010-02", "2010-03", "2010-04", "2010-05")
v2 <- c("A", "B", "C", "D", "E")
dates <- as.factor(sample(v1, 1000, replace = TRUE, prob = c(0.5, 0.2, 0.1, 0.1, 0.1)))
types <- as.factor(sample(v2, 1000, replace = TRUE, prob = c(0.3, 0.2, 0.1, 0.1, 0.1)))
var <- rnorm(1000, 10, 10)
problem_data <- data.frame(var, dates, types)
  •  Tags:  
  • Related