首页 > 解决方案 > 无法合并数据框

问题描述

我正在尝试将三个具有日期列的数据框收集在一起。我正在使用rbind(),我得到这个错误:

字符串不是模棱两可的形式

在第二个 df 中,日期列是字符类型。其他的都是POSIXlt。我知道这是问题所在,但不知道如何解决。有人可以帮忙吗?

另外,您是否有任何教程可以教 POSIXlt 是什么以及它有什么作用?

标签: r

解决方案


POSIXlt 和 POSIXct 是 R 中日期时间的两种内置数据类型。这个问答有更多解释。

在引擎盖下,两者都描述了自 1970 年第一刻以来经过的时间量。

这里我定义了两个 POSIXlt 值。我在 PST 时区,比格林威治标准时间晚 8 小时,所以我选择的第一个日期时间实际上与格林威治标准时间 1970-01-01 00:00 相同

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 秒),而大约 16 亿秒有现在过去了。

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"

如果您需要特定时间格式的它们,请参阅此处以查看使用该strptime功能的人:


推荐阅读