繁体   English   中英

从r中的以下行值填充空单元格

[英]Fill Empty cells from the below row values in r

我有如下数据

col1  col2  col3


56    78    89

67     76   43

我想在r中填充如下的空单元格

col1  col2  col3
56    78    89        
56    78    89        
56    78    89
67    76    43    
67    76    43

我们需要将空白单元格( "" )更改为NA ,然后使用zoo na.locf

library(zoo)
df1[] <- lapply(df1, function(x) as.numeric(na.locf(replace(x, x=="", NA), fromLast=TRUE)))
df1
#  col1 col2 col3
#1   56   78   89
#2   56   78   89
#3   56   78   89
#4   67   76   43
#5   67   76   43

数据

df1 <- structure(list(col1 = c("", "", "56", "", "67"), col2 = c("", 
 "", "78", "", "76"), col3 = c("", "", "89", "", "43")), .Names = c("col1", 
 "col2", "col3"), row.names = c(NA, -5L), class = "data.frame")

用另一种解决方案filltidyr

library(dplyr)
library(tidyr)

df %>%
  mutate_all(as.numeric) %>%
  fill(names(.), .direction = "up") 

结果:

  col1 col2 col3
1   56   78   89
2   56   78   89
3   56   78   89
4   67   76   43
5   67   76   43

数据:

df = structure(list(col1 = c("", "", "56", "", "67"), col2 = c("", 
"", "78", "", "76"), col3 = c("", "", "89", "", "43")), .Names = c("col1", 
"col2", "col3"), row.names = c(NA, -5L), class = "data.frame")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM