Rajarshi Bhadra
Rajarshi Bhadra

Reputation: 1944

Expanding dataframe by frequency using R

My problem involves manipulation inside data frame. The data I have is

data_i_have<-data.frame(Nature=c("a","b","c","d"),Freq=c(1,2,2,1),Values=c(1,4,6,2))

and the data I want is

data_i_want<-data.frame(Nature=c("a","b","b","c","c","d"),Freq=c(1,1,1,1,1,1),Values=c(1,2,2,3,3,2))

How can I achieve this? Any help would be greatly appreciated.

Upvotes: 3

Views: 105

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99341

You can do

with(data_i_have, {
    data.frame(
        Nature = rep(Nature, Freq), Freq = 1, Values = rep(Values / Freq, Freq)
    )
})
#   Nature Freq Values
# 1      a    1      1
# 2      b    1      2
# 3      b    1      2
# 4      c    1      3
# 5      c    1      3
# 6      d    1      2

Upvotes: 2

Related Questions