R 中字符串到日期转换的“标准明确日期”错误
Error with the “standard unambiguous date” for string-to-date conversion in R
所以我正在尝试这段代码,我过去曾将其用于其他数据整理任务,没有出现错误:
## Create an age_at_enrollment variable, based on the start_date per individual (i.e. I want to know an individual's age, when they began their healthcare job).
complete_dataset_1 = complete_dataset %>% mutate(age_at_enrollment = (as.Date(start_date)-as.Date(birth_date))/365.25)
但是,我不断收到此错误消息:
"Error in charToDate(x) : character string is not in a standard unambiguous format"
我认为发生此错误是因为在我使用的管理数据集中,start_date 和 birth_date 变量的格式很奇怪:
start_date birth_date
2/5/07 0:00 2/28/1992 0:00
我找不到关于为什么数据格式如此的答案,所以关于如何在不改变原始管理数据集的情况下解决这个问题有什么想法吗?
您对 as.Date
的调用中的歧义在于日期或月份是在前。要解决此问题,您可以使用 as.Date
:
的 format
参数
complete_dataset_1 = complete_dataset
%>% mutate(age_at_enrollment = (
as.Date(start_date, format="%m/%d/%Y") -
as.Date(birth_date, format="%m/%d/%Y")) / 365.25)
一种更精确的计算年差异的方法,处理闰年边缘情况,将使用 lubridate
包:
library(lubridate)
complete_dataset_1 = complete_dataset
%>% mutate(age_at_enrollment = time_length(difftime(
as.Date(start_date, format="%m/%d/%Y"),
as.Date(birth_date, format="%m/%d/%Y")), "years")
所以我正在尝试这段代码,我过去曾将其用于其他数据整理任务,没有出现错误:
## Create an age_at_enrollment variable, based on the start_date per individual (i.e. I want to know an individual's age, when they began their healthcare job).
complete_dataset_1 = complete_dataset %>% mutate(age_at_enrollment = (as.Date(start_date)-as.Date(birth_date))/365.25)
但是,我不断收到此错误消息: "Error in charToDate(x) : character string is not in a standard unambiguous format"
我认为发生此错误是因为在我使用的管理数据集中,start_date 和 birth_date 变量的格式很奇怪:
start_date birth_date
2/5/07 0:00 2/28/1992 0:00
我找不到关于为什么数据格式如此的答案,所以关于如何在不改变原始管理数据集的情况下解决这个问题有什么想法吗?
您对 as.Date
的调用中的歧义在于日期或月份是在前。要解决此问题,您可以使用 as.Date
:
format
参数
complete_dataset_1 = complete_dataset
%>% mutate(age_at_enrollment = (
as.Date(start_date, format="%m/%d/%Y") -
as.Date(birth_date, format="%m/%d/%Y")) / 365.25)
一种更精确的计算年差异的方法,处理闰年边缘情况,将使用 lubridate
包:
library(lubridate)
complete_dataset_1 = complete_dataset
%>% mutate(age_at_enrollment = time_length(difftime(
as.Date(start_date, format="%m/%d/%Y"),
as.Date(birth_date, format="%m/%d/%Y")), "years")