在 POSIXct 的向量上使用 sapply [英] Using sapply on vector of POSIXct
问题描述
我有一个可能非常简单的问题.我想从数据帧处理一列 POSIXct 对象并生成一个日期时间字符串向量.我尝试使用以下 sapply 调用
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
当我将此函数应用于列中的单个 POSIXct 对象时,我没有问题.所以我现在对问题所在感到困惑.我需要对 POSIXct 对象做一些特别的事情吗?
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?
推荐答案
format()
将采用向量参数,所以format(df$datetime,"%Y-%m-%dT%H:%M:%S")
应该可以满足您的需求.
format()
will take a vector argument, so
format(df$datetime,"%Y-%m-%dT%H:%M:%S")
should do what you need.
当您使用 sapply 时,您的对象被强制转换为数字,因此调用了错误的格式方法.您可以使用 sapply(df$datetime, function(x) format(as.POSIXct(x, origin="1970-01-01"),"%Y-%m-%dT) 将它们强制回 POSIXct%H:%M:%S"))
,但是除非你有特殊的理由使用apply
,就用上面的方法
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 use apply
, just use the method above
这篇关于在 POSIXct 的向量上使用 sapply的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!