問題
你想在數(shù)值向量、字符串向量和因子向量間做轉(zhuǎn)換。
方案
假設(shè)你剛開始有一個(gè)數(shù)值型向量n:
n <- 10:14
n
#> [1] 10 11 12 13 14
將這個(gè)數(shù)值型向量轉(zhuǎn)換為其他兩種類型(將結(jié)果保存在c和f):
# 數(shù)值型→字符串型
c <- as.character(n)
# 數(shù)值型→因子型
f <- factor(n)
# 10 11 12 13 14
將字符串型向量轉(zhuǎn)化為另外兩種:
# 數(shù)值型
as.numeric(c)
#> [1] 10 11 12 13 14
# 字符串型→因子型
factor(c)
#> [1] 10 11 12 13 14
#> Levels: 10 11 12 13 14
把一個(gè)因子轉(zhuǎn)變?yōu)橐粋€(gè)字符串型向量很簡(jiǎn)單:
# 因子型→數(shù)值型
as.character(f)
#> [1] "10" "11" "12" "13" "14"
然而,將因子轉(zhuǎn)化為數(shù)值型向量,有點(diǎn)棘手。如果你使用as.numberic,它將會(huì)給你因子編碼的數(shù)值,恐怕不是你想要的。
as.numeric(f)
#> [1] 1 2 3 4 5
# 另一種方式得到數(shù)字的編碼,如果這是你想要的:
unclass(f)
#> [1] 1 2 3 4 5
#> attr(,"levels")
#> [1] "10" "11" "12" "13" "14"
方法是,先轉(zhuǎn)化為字符串型,再轉(zhuǎn)化為數(shù)值型。
# 因子型→數(shù)值型
as.numeric(as.character(f))
#> [1] 10 11 12 13 14
原文鏈接:http://www.cookbook-r.com/Manipulating_data/Converting_between_vector_types/