我的数据如下
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
答案 0 :(得分:5)
我们需要将空白单元格(""
)更改为NA
,然后使用na.locf
中的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")
答案 1 :(得分:1)
来自fill
的{{1}}的另一个解决方案:
tidyr
<强>结果:强>
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