Using sapply on vector of POSIXct

这一生的挚爱 提交于 2020-01-02 02:35:10

问题


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?


回答1:


format() will take a vector argument, so format(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 use apply, just use the method above



来源:https://stackoverflow.com/questions/2482125/using-sapply-on-vector-of-posixct

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!