run*_*rds 2 attributes r subset filter
我有一个各种类型的数据框(数字,整数,日期,字符).
我想将其子集化为格式为"Date"的列.我该怎么做呢?
mtcars$dates = '2015-05-05'
mtcars$dates = as.Date(mtcars$dates)
#filter just gives me: newdf = mtcars$dates
Run Code Online (Sandbox Code Playgroud)
我们可以使用sapply循环遍历列,获取class列的内容,检查它是否为"日期"并使用该逻辑向量对列进行子集化.
mtcars[sapply(mtcars, class) == "Date"]
Run Code Online (Sandbox Code Playgroud)
另一种使用方式Filter:
#make a function that checks for the Date class
is.Date <- function(x) inherits(x, 'Date')
#use Filter to filter the data.frame
Filter(is.Date, mtcars)
Run Code Online (Sandbox Code Playgroud)
包purrr具有以下keep功能:
keep(mtcars, ~inherits(.x, "Date"))
Run Code Online (Sandbox Code Playgroud)
的~和.x编码允许使用的inherits每一列,而无需创建一个单独的函数或使用匿名功能.