user3375672
user3375672

Reputation: 3768

R: Expand dataframe rows

Given a 4x2 data frame such as:

df <- 
  data.frame(
  X=c(1,3,6,10),
  Y=c('A','K','K3', 'K'))

I would like to get a 10x2 row dataframe were X is 1,2,...10 (like 1:10), and Y is replicated the number of times specified in df$X, eg:

    X   Y
1   1   A
2   2   A
3   3   K
4   4   K
5   5   K
6   6   K3
7   7   K3
8   8   K3
9   9   K3
10  10  K

The only think I can think of is to build Y by looping through ´df´ like (pseudocode):

  for(i in 1:(nrow(df)-1)){
   Y <- c(Y,(rep.int(df$Y[i], df$X[i+1]-df$X[i])))}

It seems clumpsy. Maybe packages like reshape2 or splitstackshape will help me?

Upvotes: 2

Views: 404

Answers (1)

akrun
akrun

Reputation: 886938

We can use dplyr

library(dplyr)
library(tidyr)
data.frame(X= min(df$X):max(df$X)) %>% 
         left_join(., df, by = "X") %>%
         fill(Y)
#    X  Y
#1   1  A
#2   2  A
#3   3  K
#4   4  K
#5   5  K
#6   6 K3
#7   7 K3
#8   8 K3
#9   9 K3
#10 10  K

Upvotes: 1

Related Questions