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
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
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
:
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")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.