[英]R -apply- convert many columns from numeric to factor
我需要將許多數字列轉換為因子類型。 示例表:
df <- data.frame(A=1:10, B=2:11, C=3:12)
我試過申請:
cols<-c('A', 'B')
df[,cols]<-apply(df[,cols], 2, function(x){ as.factor(x)});
但結果是一個字符類。
> class(df$A)
[1] "character"
如何在不為每一列做 as.factor 的情況下做到這一點?
嘗試
df[,cols] <- lapply(df[,cols],as.factor)
問題是apply()
試圖將結果綁定到一個矩陣中,這導致將列強制為字符:
class(apply(df[,cols], 2, as.factor)) ## matrix
class(as.factor(df[,1])) ## factor
相比之下, lapply()
對列表的元素進行操作。
2017 年 11 月 9 日更新
purrr / purrrlyr 仍在開發中
類似於 Ben 的,但使用purrrlyr::dmap_at
:
library(purrrlyr)
df <- data.frame(A=1:10, B=2:11, C=3:12)
# selected cols to factor
cols <- c('A', 'B')
(dmap_at(df, factor, .at = cols))
A B C
<fctr> <fctr> <int>
1 2 3
2 3 4
3 4 5
4 5 6
5 6 7
6 7 8
7 8 9
8 9 10
9 10 11
10 11 12
您可以將您的結果放回一個數據框中,以識別這些因素:
df[,cols]<-data.frame(apply(df[,cols], 2, function(x){ as.factor(x)}))
另一種選擇,使用purrr
和dplyr
,可能比基本解決方案更具可讀性,並將數據保存在數據幀中:
這是數據:
df <- data.frame(A=1:10, B=2:11, C=3:12)
str(df)
'data.frame': 10 obs. of 3 variables:
$ A: int 1 2 3 4 5 6 7 8 9 10
$ B: int 2 3 4 5 6 7 8 9 10 11
$ C: int 3 4 5 6 7 8 9 10 11 12
我們可以使用dmap
輕松地對所有列進行dmap
:
library(purrr)
library(dplyr)
# all cols to factor
dmap(df, as.factor)
Source: local data frame [10 x 3]
A B C
(fctr) (fctr) (fctr)
1 1 2 3
2 2 3 4
3 3 4 5
4 4 5 6
5 5 6 7
6 6 7 8
7 7 8 9
8 8 9 10
9 9 10 11
10 10 11 12
而同樣使用dmap
使用列的子集select
從dplyr
:
# selected cols to factor
cols <- c('A', 'B')
df[,cols] <-
df %>%
select(one_of(cols)) %>%
dmap(as.factor)
要獲得所需的結果:
str(df)
'data.frame': 10 obs. of 3 variables:
$ A: Factor w/ 10 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10
$ B: Factor w/ 10 levels "2","3","4","5",..: 1 2 3 4 5 6 7 8 9 10
$ C: int 3 4 5 6 7 8 9 10 11 12
一個簡單但有效的選擇是mapply
df <- data.frame(A=1:10, B=2:11, C=3:12)
cols <- c('A', 'B')
df[,cols] <- as.data.frame(mapply(as.factor,df[,cols]))
您還可以使用 for 循環來實現相同的結果:
for(col in cols){
df[,col] <- as.factor(df[,col])
}
這里有幾個tidyverse
選項 -
library(dplyr)
cols <- c('A', 'B')
df <- df %>% mutate(across(all_of(cols), factor))
str(df)
#'data.frame': 10 obs. of 3 variables:
# $ A: Factor w/ 10 levels "1","2","3","4",..: 1 2 3 4 5 6 7 8 9 10
# $ B: Factor w/ 10 levels "2","3","4","5",..: 1 2 3 4 5 6 7 8 9 10
# $ C: int 3 4 5 6 7 8 9 10 11 12
使用map
-
df[cols] <- purrr::map(df[cols], factor)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.