Max date in R column with sapply

半城伤御伤魂 提交于 2019-12-20 06:35:40

问题


I am trying to use sapply to get the max date in a column but it is returning a number instead of a date. Any idea how to resolve this? I can't seem to figure out why this is occurring..

 mtcars$datecolm = '2015-03-03'
 mtcars$datecolm[1] = '2015-09-09'
  mtcars$datecolm = as.Date(mtcars$datecolm)

    sapply(mtcars, max)   # why is it returning a number instead of a date??
    max(mtcars$datecolm)   # works correctly

Please use sapply given the way I have set this up... I know this works with apply(mtcars,2,max).


回答1:


We need to use lapply instead of sapply

lapply(mtcars, max)

as sapply returns a vector because of the simplify=TRUE default argument and vector can hold only a single class. As there are numeric columns, the 'Date' column (which is stored as integer) gets coerced to integer value. However, we can still use sapply if we use simplify = FALSE to return a list.

sapply(mtcars, max, simplify = FALSE)

Regarding the use of apply

apply(mtcars,2,max)

I would not recommend using apply as this will convert to matrix and matrix can hold only a single class. Here, it will be all character output as the 'Date' class got converted to character.


Regarding the problem mentioned by OP in the comments, when we have output that belong to different class, we could either use list or data.frame (as data.frame is a list) as c i.e. concatenate returns a vector and as mentioned above, it can hold only a single class.

do.call(rbind, lapply(mtcars, function(x) 
          data.frame(Class=class(x), Max=max(x, na.rm=TRUE))))


来源:https://stackoverflow.com/questions/38259314/max-date-in-r-column-with-sapply

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