R 应用生成转换(POSIXct)
我在一个带有POSIXct对象的data.frame上使用apply。 问题是apply从将输入data.frame转换为.matrix()开始(根据)。这意味着POSIXct将被铸造成char 我用lappy来解决我的问题。然而,是否有更好的解决方案R 应用生成转换(POSIXct),r,type-conversion,apply,R,Type Conversion,Apply,我在一个带有POSIXct对象的data.frame上使用apply。 问题是apply从将输入data.frame转换为.matrix()开始(根据)。这意味着POSIXct将被铸造成char 我用lappy来解决我的问题。然而,是否有更好的解决方案 # data.frame with one column of posixct pos = data.frame(dateTime = c(Sys.time(), Sys.time(), Sys.time())) str(
# data.frame with one column of posixct
pos = data.frame(dateTime = c(Sys.time(), Sys.time(), Sys.time()))
str(pos) # POSIXct
test = function(x){
str(x[1])
return(x)
}
res = data.frame(apply(pos, 2, test))
str(res) # all strings
res2 = data.frame(lapply(pos, test))
str(res2) # all POSIXct
您可以使用
purr
软件包中的map\u df
功能。map
函数对于不同的输出类型有不同的版本,因此在这种情况下,您可以使用map\u df
# data.frame with one column of posixct
pos = data.frame(dateTime = c(Sys.time(), Sys.time(), Sys.time()))
str(pos) # POSIXct
test = function(x){
str(x[1])
return(x)
}
res = data.frame(apply(pos, 2, test))
str(res) # all strings
res2 = data.frame(lapply(pos, test))
str(res2) # all POSIXct
library(purrr)
res3 = map_df(pos, test)
str(res3)