0

I have a column in my data frame that looks like this:

Sally
NA
NA
Bob
NA
Jill
NA
NA

Using R code, how can I get it to look like this instead:

Sally
Sally
Sally
Bob
Bob
Jill
Jill 
Jill

Thanks

UPDATE: I wrote my own function "FillMe(x)" where the input is the column.

FillMe = function(x) {
  empty = c()
  for (i in x){

if (is.na(i) == F) {
  empty = c(empty,i)
} else {
  y = empty[length(empty)]
  empty = c(empty,y)
}
  }
  return(empty)
}
Zyferion
  • 149
  • 2
  • 11

2 Answers2

3

we can use na.locf

library(zoo)
df1$Col <- na.locf(df1$Col)
df1$Col
#[1] "Sally" "Sally" "Sally" "Bob"   "Bob"   "Jill"  "Jill"  "Jill"  

Or without using any packages

with(df1, ave(Col, cumsum(!is.na(Col)), FUN = function(x) x[!is.na(x)]))
#[1] "Sally" "Sally" "Sally" "Bob"   "Bob"   "Jill"  "Jill"  "Jill" 

data

 df1 <- structure(list(Col = c("Sally", NA, NA, "Bob", NA, "Jill", NA, 
NA)), .Names = "Col", class = "data.frame", row.names = c(NA, -8L))
akrun
  • 874,273
  • 37
  • 540
  • 662
1

Here is a tidyr option:

# using the data provided by @akrun
df1 <- structure(list(Col = c("Sally", NA, NA, "Bob", NA, "Jill", NA, 
                              NA)), .Names = "Col", class = "data.frame", row.names = c(NA, -8L))

# we load tidyr, install.packages("tidyr") if you don't have it yet
library(tidyr)

# then fill does the job - fill(df1, 1) works fine as well
fill(df1, Col)

> fill(df1, Col)
Col
1 Sally
2 Sally
3 Sally
4   Bob
5   Bob
6  Jill
7  Jill
8  Jill
Vincent Bonhomme
  • 7,235
  • 2
  • 27
  • 38