Manipulating Data - 重計算數(shù)據(jù)框所有因子列的水平

重計算數(shù)據(jù)框所有因子列的水平

問題

你想要重新計算一個數(shù)據(jù)框中所有因子列(變量)的因子水平。

方案

有時候在讀入和清理數(shù)據(jù)之后,你會發(fā)現(xiàn)數(shù)據(jù)(數(shù)據(jù)框)結(jié)果中有的因子列有一些不存在的因子水平。

例如,下面的d有一個空行。當(dāng)它被讀入時,因子列會出現(xiàn)""水平,它不應(yīng)該是數(shù)據(jù)的一部分。

d <- read.csv(header = TRUE, text='
x,y,value
a,one,1
,,5
b,two,4
c,three,10
')

d
#>   x     y value
#> 1 a   one     1
#> 2             5
#> 3 b   two     4
#> 4 c three    10

str(d)
#> 'data.frame':    4 obs. of  3 variables:
#>  $ x    : Factor w/ 4 levels "","a","b","c": 2 1 3 4
#>  $ y    : Factor w/ 4 levels "","one","three",..: 2 1 4 3
#>  $ value: int  1 5 4 10

即便移除了空行,因子中仍有""水平:

# 移除第二行
d <- d[-2,]
d
#>   x     y value
#> 1 a   one     1
#> 3 b   two     4
#> 4 c three    10

str(d)
#> 'data.frame':    3 obs. of  3 variables:
#>  $ x    : Factor w/ 4 levels "","a","b","c": 2 3 4
#>  $ y    : Factor w/ 4 levels "","one","three",..: 2 4 3
#>  $ value: int  1 4 10

使用droplevels

最簡單的方式是使用droplevels()函數(shù):

d1 <- droplevels(d)
str(d1)
#> 'data.frame':    3 obs. of  3 variables:
#>  $ x    : Factor w/ 3 levels "a","b","c": 1 2 3
#>  $ y    : Factor w/ 3 levels "one","three",..: 1 3 2
#>  $ value: int  1 4 10

使用vapplylapply

為了重新計算所有因子列的水平,我們使用以is.factor()為參數(shù)的vapply()函數(shù)去找出哪些列是因子,然后再利用以factor()函數(shù)為參數(shù)的lapply()操作將那些列重新計算因子水平。

# 找出哪些列是因子
factor_cols <- vapply(d, is.factor, logical(1))

# 把factor()函數(shù)應(yīng)用到那些列,并把結(jié)果賦回d
d[factor_cols] <- lapply(d[factor_cols], factor)
str(d)
#> 'data.frame':    3 obs. of  3 variables:
#>  $ x    : Factor w/ 3 levels "a","b","c": 1 2 3
#>  $ y    : Factor w/ 3 levels "one","three",..: 1 3 2
#>  $ value: int  1 4 10

另見

關(guān)于重計算一個因子變量水平的信息,參見 ../Re-computing_the_levels_of_factor.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容