R在多个时间列的同一行中用不同的日期值替换NA
R Replacing NAs with different date values in the same row across multiple time columns
我有一个 dataset
,在 time
列中有一些 NAs
,如下面的示例数据所示。通常当我修改单个列的行值时,我使用:
df["195", "Date_Received"] = "9/1/2017"
但现在我想将值添加到所需列中的 NA 行,而不必多次编写上述语句。
请注意,原文中的列是使用 lubridate
的日期格式。
在 R
中,tidy
有什么方法可以做到这一点?
虚拟数据
Date = c("2021-11-01", "2021-11-04", NA, "2021-11-15", NA)
Year = c(2021, 2021, NA, 2021, NA)
Month = c(11, 11, NA, 11, NA)
Day = c(01, 04, NA, 15, NA)
期望的输出
Date Year Month Day
2021-11-01 2021 11 01
2021-11-04 2021 11 04
2021-11-12 2021 11 12
2021-11-15 2021 11 15
2021-12-02 2021 11 02
代码
library(tidyverse)
df = data.frame(Date, Year, Month, Day)
# Replacing NAs with date values....
我不确定您从哪里获取第 3 行和第 5 行的日期值,但是如果您有所需日期的向量,则可以直接分配它们
df = data.frame(Date=Date)
df[is.na(Date),"Date"] <- c("2021-11-12","2021-12-02")
输出:
Date
1 2021-11-01
2 2021-11-04
3 2021-11-12
4 2021-11-15
5 2021-12-02
然后您可以根据需要创建 year/month/day 列:
df %>% mutate(Year = year(Date), Month = month(Date), day=day(Date))
输出:
Date Year Month day
1 2021-11-01 2021 11 1
2 2021-11-04 2021 11 4
3 2021-11-12 2021 11 12
4 2021-11-15 2021 11 15
5 2021-12-02 2021 12 2
我有一个 dataset
,在 time
列中有一些 NAs
,如下面的示例数据所示。通常当我修改单个列的行值时,我使用:
df["195", "Date_Received"] = "9/1/2017"
但现在我想将值添加到所需列中的 NA 行,而不必多次编写上述语句。
请注意,原文中的列是使用 lubridate
的日期格式。
在 R
中,tidy
有什么方法可以做到这一点?
虚拟数据
Date = c("2021-11-01", "2021-11-04", NA, "2021-11-15", NA)
Year = c(2021, 2021, NA, 2021, NA)
Month = c(11, 11, NA, 11, NA)
Day = c(01, 04, NA, 15, NA)
期望的输出
Date Year Month Day
2021-11-01 2021 11 01
2021-11-04 2021 11 04
2021-11-12 2021 11 12
2021-11-15 2021 11 15
2021-12-02 2021 11 02
代码
library(tidyverse)
df = data.frame(Date, Year, Month, Day)
# Replacing NAs with date values....
我不确定您从哪里获取第 3 行和第 5 行的日期值,但是如果您有所需日期的向量,则可以直接分配它们
df = data.frame(Date=Date)
df[is.na(Date),"Date"] <- c("2021-11-12","2021-12-02")
输出:
Date
1 2021-11-01
2 2021-11-04
3 2021-11-12
4 2021-11-15
5 2021-12-02
然后您可以根据需要创建 year/month/day 列:
df %>% mutate(Year = year(Date), Month = month(Date), day=day(Date))
输出:
Date Year Month day
1 2021-11-01 2021 11 1
2 2021-11-04 2021 11 4
3 2021-11-12 2021 11 12
4 2021-11-15 2021 11 15
5 2021-12-02 2021 12 2