다양한 유형 (숫자, 정수, 날짜, 문자)의 데이터 프레임이 있습니다.날짜 필드 만 선택
'날짜'형식의 열만이 부분 집합으로 만들려고합니다. 어떻게해야합니까?
mtcars$dates = '2015-05-05'
mtcars$dates = as.Date(mtcars$dates)
#filter just gives me: newdf = mtcars$dates
다양한 유형 (숫자, 정수, 날짜, 문자)의 데이터 프레임이 있습니다.날짜 필드 만 선택
'날짜'형식의 열만이 부분 집합으로 만들려고합니다. 어떻게해야합니까?
mtcars$dates = '2015-05-05'
mtcars$dates = as.Date(mtcars$dates)
#filter just gives me: newdf = mtcars$dates
다른 방법 Filter
사용 :
keep(mtcars, ~inherits(.x, "Date"))
가 ~
및 .x
부호화 각 열에 inherits
를 사용할 수있다 :
#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)
우리는인지 '날짜'를 확인하고 열을 서브 세트 논리 벡터를 사용하여 컬럼의 class
를 얻을 컬럼을 통해 루프 sapply
를 사용할 수 있습니다.
mtcars[sapply(mtcars, class) == "Date"]
패키지 purrr하면 이에 대한 keep
기능을 갖는다 별도의 기능 또는 usin을 만들지 않고 g 익명의 기능.
이 작동합니다 :
data(mtcars)
mtcars$dates = '2015-05-05'
mtcars$dates = as.Date(mtcars$dates)
head(mtcars)
v=sapply(mtcars,class) #get the class of each column
datecol=names(v)[v=='Date'] # select the columns having date class
mtcars[datecol] #subset those columns.
select_if
는 데이터 프레임의 컬럼에 술어를 사용할 수 있습니다. 만 술어가 TRUE
을 반환하는 그 열이 선택됩니다 :
library(dplyr)
select_if(mtcars, function(x) inherits(x, 'Date'))
이 기본적으로 내가 질문에 대답하지만 당신은 때 나는 그의 대답을 보지 못했다 – Jaap
@akrun의 대답 (만 더 복잡한)과 동일 권리. 그의 솔루션은 더욱 우아합니다. – Nestorghh