lapply和sapply返回不同的价值

时间:2017-10-13 17:04:08

标签: r apply lapply sapply

我一直以为sapply和lapply之间的唯一区别是第一个产生矩阵而第二个产生一个列表,但差异不止于此 我设置了这样一个函数:

nadate <- function(x) {
  ifelse(is.na(x),"True",as.Date(as.character(x),format="%Y%m%d"))}

numdate <- function(x) {
  if (all(is.na(x))) return (x)
  else if(!any(is.na(nadate(x)))) {
    as.Date(as.character(x),format="%Y%m%d")}
  else return (x)}

d是

ValueDate BookDate  TranAmt
1 20161219  20161219  123123.1
2 20161216  20161216  3234.2
3 20161216  20161216  42123.3

d3 <- lapply(d, numdate) # returns what I want

   ValueDate   BookDate    TranAmt
1  2016-12-19  2016-12-19  123123.1
2  2016-12-16  2016-12-16  3234.2
3  2016-12-16  2016-12-16  42123.3


d3 <- sapply(d, numdate) # suppose to return the same value but in a matrix, but it returns completely different values
ValueDate  BookDate
1 17154      17154
2 17151      17151
3 17151      17151

0 个答案:

没有答案