[英]Fill Empty cells from the below row values in r
I have data as below 我有如下数据
col1 col2 col3
56 78 89
67 76 43
I want to fill the empty cells as below in r 我想在r中填充如下的空单元格
col1 col2 col3
56 78 89
56 78 89
56 78 89
67 76 43
67 76 43
We need to change the blank cells ( ""
) to NA
and then use na.locf
from zoo
我们需要将空白单元格(
""
)更改为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")
Another solution with fill
from tidyr
: 用另一种解决方案
fill
从tidyr
:
library(dplyr)
library(tidyr)
df %>%
mutate_all(as.numeric) %>%
fill(names(.), .direction = "up")
Result: 结果:
col1 col2 col3
1 56 78 89
2 56 78 89
3 56 78 89
4 67 76 43
5 67 76 43
Data: 数据:
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.