0

I have a dataset imported from Excel that contains data in a format similar to the example below:

var1 <- c("F3.1", NA, NA, NA, NA, "F3.2", NA, NA, NA, "F4.2", "F4.3", NA, NA)
var2 <- letters[1:13]
df <- data.frame(var1, var2)
df

   var1 var2
1  F3.1    a
2  <NA>    b
3  <NA>    c
4  <NA>    d
5  <NA>    e
6  F3.2    f
7  <NA>    g
8  <NA>    h
9  <NA>    i
10 F4.2    j
11 F4.3    k
12 <NA>    l
13 <NA>    m

I would like to expand var1 rowwise, so the final output would look like this:

   var1 var2
1  F3.1    a
2  F3.1    b
3  F3.1    c
4  F3.1    d
5  F3.1    e
6  F3.2    f
7  F3.2    g
8  F3.2    h
9  F3.2    i
10 F4.2    j
11 F4.3    k
12 F4.3    l
13 F4.3    m

I've tried writing some sort of loop with if (is.na(var1)) {copy previous value} else {var1}, but haven't figured it out yet. I've also looked at expand(), but found it hard to apply to this case, because I have no other variable to group on. Lastly: The example is just an example; I'm importing lots of Excels with this layout, so I'm looking for a way to execute this as automatic as possible.

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
Demi
  • 33
  • 1
  • 5

1 Answers1

0
library(tidyr)

df %>% fill(var1)

will do the job. See here.

Sascha
  • 194
  • 7