r - 无法合并数据框
问题描述
我正在尝试将三个具有日期列的数据框收集在一起。我正在使用rbind()
,我得到这个错误:
字符串不是模棱两可的形式
在第二个 df 中,日期列是字符类型。其他的都是POSIXlt。我知道这是问题所在,但不知道如何解决。有人可以帮忙吗?
另外,您是否有任何教程可以教 POSIXlt 是什么以及它有什么作用?
解决方案
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
功能的人:
推荐阅读
- wix - Wix 使用自定义操作执行命令不起作用
- ruby-on-rails - 如何在 ruby .rb 文件方法中的两个字符串之间添加多个空格以生成 pdf?
- algorithm - 如何转换一条线以满足最小转弯半径标准?
- php - 如何修复 .htaccess 权限以解决错误 500?
- asp.net-core - IIS 10.0 详细错误 500.19 错误代码:0x8007000d
- python - xgboost - 我预测测试数据时的功能不匹配
- django - django admin 的样式未显示
- json - 需要使用 JOLT 在 JSON 中进行日期字段转换(将日期“1118083350”转换为日期:18/11/2020 和时间:053350)
- node.js -
- node.js - 错误:eslint-bridge Node.js 进程无响应。这很可能是由于进程内存不足引起的