在 POSIXct 向量上使用 sapply
我有一个可能非常简单的问题。我想处理数据帧中的一列 POSIXct 对象并生成日期时间字符串向量。我尝试使用以下 sapply 调用
dt <- sapply(df$datetime, function(x) format(x,"%Y-%m-%dT%H:%M:%S"))
但无济于事。我不断收到以下错误:
> Error in prettyNum(.Internal(format(x, trim, digits, nsmall, width, 3L, :
invalid 'trim' argument
当我将此函数应用于列中的单个 POSIXct 对象时,没有问题。所以我现在很困惑问题是什么。我需要对 POSIXct 对象做一些特殊的事情吗?
I have what may be a very simple question. I want to process a column of POSIXct objects from a dataframe and generate a vector of datetime strings. I tried to use the following sapply call
dt <- sapply(df$datetime, function(x) format(x,"%Y-%m-%dT%H:%M:%S"))
but to no avail. I keep getting the following error:
> Error in prettyNum(.Internal(format(x, trim, digits, nsmall, width, 3L, :
invalid 'trim' argument
When I apply this function to a single POSIXct object from the column, I have no problem. So I'm stumped at the moment about what the problem is. Do I need to do something special with POSIXct objects?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
format()
将采用向量参数,因此format(df$datetime,"%Y-%m-%dT%H:%M:%S")
应该满足您的需要。当您使用 sapply 时,您的对象被强制为数字,因此调用了错误的格式方法。您可以使用
sapply(df$datetime, function(x) format(as.POSIXct(x, origin="1970-01-01"),"%Y-%m-%dT %H:%M:%S"))
,但是除非你有特殊原因需要使用apply
,就使用上面的方法format()
will take a vector argument, soformat(df$datetime,"%Y-%m-%dT%H:%M:%S")
should do what you need.When you use sapply, your objects are coerced to numeric, and so the wrong format method is being invoked. You could coerce them back to POSIXct by using
sapply(df$datetime, function(x) format(as.POSIXct(x, origin="1970-01-01"),"%Y-%m-%dT%H:%M:%S"))
, but unless you have a special reason to useapply
, just use the method above