【发布时间】:2021-04-15 20:43:34
【问题描述】:
我正在尝试将三个具有日期列的数据框收集在一起。我正在使用 rbind() 并收到此错误:
字符串不是模棱两可的形式
在第二个df中,日期列是字符类型。其他的都是POSIXlt。我知道这是问题所在,但不知道如何解决。有人可以帮忙吗?
另外,你们有什么教程教什么是 POSIXlt 以及它有什么作用?
【问题讨论】:
标签: r
我正在尝试将三个具有日期列的数据框收集在一起。我正在使用 rbind() 并收到此错误:
字符串不是模棱两可的形式
在第二个df中,日期列是字符类型。其他的都是POSIXlt。我知道这是问题所在,但不知道如何解决。有人可以帮忙吗?
另外,你们有什么教程教什么是 POSIXlt 以及它有什么作用?
【问题讨论】:
标签: r
POSIXlt 和 POSIXct 是 R 中日期时间的两种内置数据类型。This Q&A 有更多解释。
在幕后,两者都描述了自 1970 年第一刻以来所经过的时间。
在这里我定义了两个 POSIXlt 值。我在 PST 时区,比 GMT 晚 8 小时,所以我选择的第一个日期时间实际上与 1970-01-01 00:00 GMT 相同
my_times <- as.POSIXlt(c("1969-12-31 16:00", "2021-04-15 13:49"))
my_times
#[1] "1969-12-31 16:00:00 PST" "2021-04-15 13:49:00 PDT"
在底层,POSIXlt 格式的每个时间戳都是一个数字列表,每个数字都描述了年份、日期、小时等,并带有一些额外的标志来告诉 R 它是一个 POSIXlt、我的时区以及它是否是夏令时,等等
# dput creates code that would reproduce those values. You'll see that
# it encodes them by coding the year, month, day, hour, etc.
dput(my_times)
#structure(list(sec = c(0, 0), min = c(0L, 49L), hour = c(16L,
#13L), mday = c(31L, 15L), mon = c(11L, 3L), year = c(69L, 121L
#), wday = 3:4, yday = c(364L, 104L), isdst = 0:1, zone = c("PST",
#"PDT"), gmtoff = c(NA_integer_, NA_integer_)), class = c("POSIXlt",
#"POSIXt"))
# FYI, POSIXct stores the numbers directly as seconds since 1970
# (equivalent to the way POSIXct stores them)
structure(c(0, 1618519740), class = c("POSIXct", "POSIXt"), tzone = "")
如果我们需要将这两个时间戳分别转换为一个数字,R 会将其转换为自 1970 年初以来的秒数。第一个被选为那个时刻(经过 0 秒),而大约 1.6现在已经过去了十亿秒。
as.numeric(my_times)
#[1] 0 1618519740
# approx years since start of 1970
# calculated by looking at the difference between the two numbers
diff(as.numeric(my_times))/(24*60*60*365.25)
#[1] 51.2878
要转换为字符,您可以使用as.character 来获取它们:
as.character(my_times)
#[1] "1969-12-31 16:00:00" "2021-04-15 13:49:00"
如果您需要特定时间格式的它们,请在此处查看review of those using the strptime function:
【讨论】:
为此安装 lubridate 软件包。
如果数组具有不同的数据类型,它们将不会绑定。将所有三个 Date 列转换为相同的类型:
df1$DATE = as.Date(df1$DATE ,"%Y-%m-%d")
如果日期格式为"2021-04-16" ;;将"%m-%d-%Y" 用于04-16-2021,将"%d-%b-%Y" 用于04-Apr-2021。如果日期格式为 "04/16/2021",则将 "-" 替换为 "/"
然后 ,
同样,
df2$DATE = as.Date(df2$DATE ,"%Y-%m-%d")
df3$DATE = as.Date(df2$DATE ,"%Y-%m-%d")
然后,调用
df_final = rbind(df1 ,df2 ,df3)
【讨论】: