如何根据以前的值复制值

时间:2014-04-06 16:37:06

标签: r function replicate

如何根据以前的值复制一个值?

e.g

我的数据集

name <- c("sergio",NA,NA,NA,NA,"John", NA,NA,NA,NA,NA,NA)
number <-c(1234,NA,NA,NA,NA,5678, NA,NA,NA,NA,NA,NA) 
mydata <- cbind(as.data.frame(name),as.data.frame(number))

新数据集

name     number
sergio    1234
sergio    1234
sergio    1234
sergio    1234 
John      5678
John      5678 
John      5678 
John      5678
John      5678 
John      5678
....

2 个答案:

答案 0 :(得分:3)

您可以使用&#34;动物园中的na.locf&#34;包:

mydata <- data.frame(
  name = c("sergio",NA,NA,NA,NA,"John", NA,NA,NA,NA,NA,NA),
  number = c(1234,NA,NA,NA,NA,5678, NA,NA,NA,NA,NA,NA))

library(zoo)
na.locf(mydata)
#      name number
# 1  sergio   1234
# 2  sergio   1234
# 3  sergio   1234
# 4  sergio   1234
# 5  sergio   1234
# 6    John   5678
# 7    John   5678
# 8    John   5678
# 9    John   5678
# 10   John   5678
# 11   John   5678
# 12   John   5678

如果您不想使用套餐,可以采取以下措施:

LOCF <- function(x) {
  A <- cumsum(!is.na(x))
  ave(x, A, FUN = function(x) x[1])
}

mydata[] <- lapply(mydata, LOCF)

答案 1 :(得分:1)

您还可以使用简单的自制功能:

copydown <- function(x) {
   for(iii in seq_along(x)[-1]) if(is.na(x[iii])) x[iii]<- x[iii-1]
   x
}
> copydown(name)
# [1] "sergio" "sergio" "sergio" "sergio" "sergio" "John"   "John"   "John"  
# [9] "John"   "John"   "John"   "John"
mydata[] <- lapply(mydata, copydown)
# notice [] -- so the result will be a data frame rather than a list