簡體   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