R - Retrieve distribution from histogram data

dataframe, histogram, r

Solution

You can combine functions `apply()` and `rep()`. In `rep()` you use columns A and B to set `time=` to repeat `Value`.

apply(df[,-1],2,function(x) rep(df$Value,times=x))
$A
[1] 0 0 0 1 1

$B
[1] 0 1 1 1 1 2 2

Update

As pointed out by @Arun function `apply()` will coerce data frame to matrix before applying function and that is not necessary. In this case the same result can be achieved with function `lapply()` because we apply function to columns.

lapply(df[,-1],function(x) rep(df$Value,times=x))
$A
[1] 0 0 0 1 1

$B
[1] 0 1 1 1 1 2 2

Problem

I have this kind of data frame: ``` df<-data.frame(Value=c(0,1,2), A=c(3,2,0), B=c(1,4,2)) ``` I want to get vectors with the distribution of my values for each groups (A,B) considering that numbers in each column correspond to the number of occurence of each "value" (data from histogram). So If I have 5 in the A column for the value 1, I want to have five 1 (1,1,1,1,1) in the vector result. In the example, the result would be:: ``` A<-c(0,0,0,1,1) B<-c(0,1,1,1,1,2,2) ``` Thx

Original source