R:用之前的非NA条目替换NA条目

时间:2016-05-02 04:52:07

标签: r replace dataframe na

我的数据框中有一列如下所示:

Sally
NA
NA
Bob
NA
Jill
NA
NA

使用R代码,我怎样才能让它看起来像这样:

Sally
Sally
Sally
Bob
Bob
Jill
Jill 
Jill

由于

更新:我写了自己的功能" FillMe(x)"输入是列的位置。

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)
}

2 个答案:

答案 0 :(得分:3)

我们可以使用na.locf

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

或者不使用任何包

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

数据

 df1 <- structure(list(Col = c("Sally", NA, NA, "Bob", NA, "Jill", NA, 
NA)), .Names = "Col", class = "data.frame", row.names = c(NA, -8L))

答案 1 :(得分:1)

以下是tidyr选项:

# 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