R - obtaining distribution according to the histogram

I have this data format:

df<-data.frame(Value=c(0,1,2), A=c(3,2,0), B=c(1,4,2)) 

I want to get vectors with a distribution of my values ​​for each group (A, B), assuming that the numbers in each column correspond to the number of occurrences of each β€œvalue” (data from a histogram). So, if I have 5 in column A for a value of 1, I want to have five 1 (1,1,1,1,1,1) in the vector result. In this example, the result would be:

  A<-c(0,0,0,1,1) B<-c(0,1,1,1,1,2,2) 

thanks

+4
source share
1 answer

You can combine the apply() and rep() functions. 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 indicated in the @Arun apply() function, it will force the data frame to the matrix before applying the function, and this is optional. In this case, the same result can be achieved using the lapply() function, because we apply the function to the 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 
+4
source

Source: https://habr.com/ru/post/1495504/


All Articles