Search code examples
rfrequency

Value data and Count data in two separate columns - I'd like to get one column of Frequency data


I have observations in Value and Count form (frequency information)

value<- c(0,1,3,6,7,8) count <-c (3,2,1,1,1,3)

I want the data ("value") in one column, where I have 3 counts of 0, and 2 counts of 1, one count of 3 etc. I want all of my raw values in one column. Like this:

freq_of_values <- c(0, 0, 0, 1, 1, 3, 6, 7, 8, 8, 8)

value<- c(0,1,3,6,7,8)
count <- c(3,2,1,1,1,3)

I've searched and tried the (dplyr) merge and sort functions but am not getting what I want. Perhaps my terminology while searching wasn't just right. Appreciate any help!!


Solution

  • We can use rep with times as 'count' vector

    rep(value, times = count)
    #[1] 0 0 0 1 1 3 6 7 8 8 8
    

    If the initial data is data.frame

     df1 <- data.frame(value, count)
    

    create a new data.frame with

    df2 <- data.frame(freq_of_values = rep(df1$value, df1$count))
    

    Or using uncount from tidyr

    library(tidyr)
    library(dplyr)
    uncount(df1, count) %>%
       rename(freq_of_values = value) %>%
       as_tibble