R 在apply中解析datetimes,返回数值而不是日期对象
也许我设计得太过火了,但我正在构建一个函数,根据输入的列数自动解析日期列 数据: 但是当我使用多个列时(例如R 在apply中解析datetimes,返回数值而不是日期对象,r,date,apply,R,Date,Apply,也许我设计得太过火了,但我正在构建一个函数,根据输入的列数自动解析日期列 数据: 但是当我使用多个列时(例如df[,c(1,2)]或df[,c('CreatedDate','LastModifiedDate')],我会得到: CreatedDate LastModifiedDate [1,] 16759 16759 [2,] 16760 16770 [3,] 16760 16760 [
df[,c(1,2)]
或df[,c('CreatedDate','LastModifiedDate')]
,我会得到:
CreatedDate LastModifiedDate
[1,] 16759 16759
[2,] 16760 16770
[3,] 16760 16760
[4,] 16760 16760
[5,] 16760 16760
为什么单个向量正确返回格式中的日期值,而应用不正确?这里的lappy
,rbind
方法会更好吗?
只是试着去理解这些行为。试试这个:
parse_sf_hms <- function(subset) {
if( is.null( ncol(subset) ) ){
subset %>% ymd_hms(tz="America/New_York",quiet=TRUE) %>% as.Date(format="%m/%d/%Y") -> x
return(x)
} else {
x <- lapply(subset, function(x) x %>% ymd_hms(tz="America/New_York",quiet=TRUE) %>% as.Date(format="%m/%d/%Y") )
return( x )
}
}
需要分配给x
:
x <- lapply(subset, function(x) x %>% ymd_hms(tz="America/New_York",quiet=TRUE) %>% as.Date(format="%m/%d/%Y") )
x%ymd\u hms(tz=“美国/纽约”,quiet=TRUE)%>%as.Date(format=“%m/%d/%Y”))
不要使用apply(subset,2,FUN)
因为它使所有内容都成为一个矩阵,从而强制将日期恢复为数字。尝试lappy(subset,FUN)
。谢谢@thelatemail-这回答了我关于行为的问题中最重要的部分。
parse_sf_hms <- function(subset) {
if( is.null( ncol(subset) ) ){
subset %>% ymd_hms(tz="America/New_York",quiet=TRUE) %>% as.Date(format="%m/%d/%Y") -> x
return(x)
} else {
x <- lapply(subset, function(x) x %>% ymd_hms(tz="America/New_York",quiet=TRUE) %>% as.Date(format="%m/%d/%Y") )
return( x )
}
}
apply(subset, 2, function(x) x %>% ymd_hms(tz="America/New_York",quiet=TRUE) %>% as.Date(format="%m/%d/%Y") )
x <- lapply(subset, function(x) x %>% ymd_hms(tz="America/New_York",quiet=TRUE) %>% as.Date(format="%m/%d/%Y") )