R列中的最高日期与sapply [英] Max date in R column with sapply

查看:66
本文介绍了R列中的最高日期与sapply的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用sapply获取列中的最大日期,但它返回的是数字而不是日期.任何想法如何解决这个问题?我似乎不知道为什么会这样.

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

请按照我已设置的方式使用sapply ...我知道这适用于apply(mtcars,2,max).

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

推荐答案

我们需要使用lapply而不是sapply

lapply(mtcars, max)

由于simplify=TRUE的默认参数,

as sapply返回vector,而vector只能容纳一个类.由于存在数字列,因此日期"列(存储为整数)被强制为integer值.但是,如果我们使用simplify = FALSE返回list,我们仍然可以使用sapply.

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)

关于apply

apply(mtcars,2,max)

我不建议使用apply,因为它将转换为矩阵并且矩阵只能容纳一个类.在这里,所有的character输出都将作为日期"类被转换为character的.

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.

关于OP在注释中提到的问题,当我们拥有属于不同类的输出时,我们可以使用listdata.frame(因为data.framelist)作为c,即concatenate返回vector,如上所述,它只能容纳一个类.

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))))

这篇关于R列中的最高日期与sapply的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆