데이터 프레임에서 숫자 열만 선택
다음과 같은 data.frame이 있다고 가정합니다.
x <- data.frame(v1=1:20,v2=1:20,v3=1:20,v4=letters[1:20])
x에 숫자로 표시된 열만 선택하려면 어떻게 해야 합니다.
편집: 잘못된 사용을 방지하기 위해 업데이트됨sapply
.
데이터 프레임은 목록이므로 list-apply 함수를 사용할 수 있습니다.
nums <- unlist(lapply(x, is.numeric), use.names = FALSE)
그런 다음 표준 부분 집합 설정
x[ , nums]
## don't use sapply, even though it's less code
## nums <- sapply(x, is.numeric)
좀 더 관용적인 현대식 R을 추천합니다.
x[ , purrr::map_lgl(x, is.numeric)]
코드가 적고, R의 특정 특성을 덜 반영하며, 데이터베이스 백엔드 경골에서 사용하기에 더 간단하고 강력합니다.
dplyr::select_if(x, is.numeric)
최신 버전의 dplyr은 다음 구문도 지원합니다.
x %>% dplyr::select(where(is.numeric))
dplyr 패키지의select_if(
) 함수는 우아한 솔루션입니다.
library("dplyr")
select_if(x, is.numeric)
Filter()
기본 패키지는 해당 사용 사례에 대한 완벽한 기능입니다.코드화하기만 하면 됩니다.
Filter(is.numeric, x)
그것은 또한 훨씬 빠릅니다.select_if()
:
library(microbenchmark)
microbenchmark(
dplyr::select_if(mtcars, is.numeric),
Filter(is.numeric, mtcars)
)
(내 컴퓨터에서) 60마이크로초의 중앙값을 반환합니다.Filter
의 경우 21,000마이크로초select_if
(350배 더 빠름).
열 이름에만 관심이 있는 경우 다음을 사용합니다.
names(dplyr::select_if(train,is.numeric))
iris %>% dplyr::select(where(is.numeric)) #as per most recent updates
의 다른 옵션purrr
부정하는 것일 것입니다.discard
함수:
iris %>% purrr::discard(~!is.numeric(.))
숫자 열의 이름을 원하는 경우 추가할 수 있습니다.names
또는colnames
:
iris %>% purrr::discard(~!is.numeric(.)) %>% names
이 코드는 다른 답변에 대한 대체 코드입니다.
x[, sapply(x, class) == "numeric"]
와 함께data.table
x[, lapply(x, is.numeric) == TRUE, with = FALSE]
library(purrr)
x <- x %>% keep(is.numeric)
PCAmix 데이터 라이브러리에는 아래와 같이 주어진 데이터 프레임 "YourDataframe"의 정량적(수치 데이터)과 정성적(범주 데이터)을 분할하는 분할 혼합 기능이 있습니다.
install.packages("PCAmixdata")
library(PCAmixdata)
split <- splitmix(YourDataframe)
X1 <- split$X.quanti(Gives numerical columns in the dataset)
X2 <- split$X.quali (Gives categorical columns in the dataset)
요인 변수가 많은 경우 사용할 수 있습니다.select_if
기능dplyr 패키지를 설치합니다.조건을 만족하여 데이터를 분리하는 기능이 많이 있습니다.조건을 설정할 수 있습니다.
이렇게 사용합니다.
categorical<-select_if(df,is.factor)
str(categorical)
또 다른 방법은 다음과 같습니다.
#extracting numeric columns from iris datset
(iris[sapply(iris, is.numeric)])
Numerical_variables <- which(sapply(df, is.numeric))
# then extract column names
Names <- names(Numerical_variables)
이 방법은 질문에 직접적으로 대답하지는 않지만 특히 ID 열과 종속 변수를 제외한 모든 숫자 열과 같은 것을 원하는 경우 매우 유용할 수 있습니다.
numeric_cols <- sapply(dataframe, is.numeric) %>% which %>%
names %>% setdiff(., c("id_variable", "dep_var"))
dataframe %<>% dplyr::mutate_at(numeric_cols, function(x) your_function(x))
언급URL : https://stackoverflow.com/questions/5863097/selecting-only-numeric-columns-from-a-data-frame
'programing' 카테고리의 다른 글
목록에 추가하는 것보다 목록 이해가 훨씬 빠른 이유는 무엇입니까? (0) | 2023.06.10 |
---|---|
Apache POI를 사용하여 내 xlsx 시트를 Java 개체로 변환하는 방법 (0) | 2023.06.10 |
루비: 포함과 반대되는 것이 있습니까?Ruby Arrays의 경우? (0) | 2023.06.05 |
'webpack-cli' 모듈을 찾을 수 없습니다. (0) | 2023.06.05 |
Python에서 중첩된 딕트를 어떻게 생성합니까? (0) | 2023.06.05 |