在数据框R的日期列中填写NA [英] FIll up NA s in date column of dataframe R
本文介绍了在数据框R的日期列中填写NA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的数据如下:
> sample
ID Date
1 1 NA
2 1 NA
3 1 16436
4 1 NA
5 2 NA
6 2 16436
7 2 NA
8 2 NA
我想要的数据集
> final
ID Date
1 1 <NA>
2 1 <NA>
3 1 2015-01-01
4 1 <NA>
5 2 <NA>
6 2 2015-01-01
7 2 2015-01-01
8 2 2015-01-01
我正在使用的代码是
> final <- sample %>%
+ group_by(ID) %>%
+ mutate(Date = zoo:: na.locf(as.Date(Date,origin= "1970-01-01")))
Error: incompatible size (2), expecting 4 (the group size) or 1
在此问题上的任何帮助将不胜感激
Any help on the issue will be greatly appreciated
推荐答案
我们需要 na .rm = FALSE
。默认情况下,它是 na.rm = TRUE
,它会在开始时删除 NA
值,以便输出具有比原始数据集中的元素数量少。 dplyr :: mutate
仅在输出元素的长度与原始数据集的 length
相同时有效。
We need the na.rm=FALSE
. By default, it is na.rm=TRUE
which removes the NA
values at the beginning so that the output will have less number of elements than in the original dataset. The dplyr::mutate
will only work when the output elements have the same length
as the original dataset.
library(zoo)
library(dplyr)
sample %>%
group_by(ID) %>%
mutate(Date = na.locf(as.Date(Date, origin = '1970-01-01'), na.rm=FALSE))
# ID Date
# (int) (date)
#1 1 <NA>
#2 1 <NA>
#3 1 2015-01-01
#4 1 2015-01-01
#5 2 <NA>
#6 2 2015-01-01
#7 2 2015-01-01
#8 2 2015-01-01
这篇关于在数据框R的日期列中填写NA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文