尝试这个:
> key <- factor(state.abb)
> key
[1] AL AK AZ AR CA CO CT DE FL GA HI ID IL IN IA KS KY LA ME MD MA MI MN MS MO MT
[27] NE NV NH NJ NM NY NC ND OH OK OR PA RI SC SD TN TX UT VT VA WA WV WI WY
50 Levels: AK AL AR AZ CA CO CT DE FL GA HI IA ID IL IN KS KY LA MA MD ME ... WY
如果您想要每个替代值并希望保留所有因子水平,请使用:
> split(key, 1:length(key) %% 2 == 0)
$`FALSE`
[1] AL AZ CA CT FL HI IL IA KY ME MA MN MO NE NH NM NC OH OR RI SD TX VT WA WI
50 Levels: AK AL AR AZ CA CO CT DE FL GA HI IA ID IL IN KS KY LA MA MD ME ... WY
$`TRUE`
[1] AK AR CO DE GA ID IN KS LA MD MI MS MT NV NJ NY ND OK PA SC TN UT VA WV WY
50 Levels: AK AL AR AZ CA CO CT DE FL GA HI IA ID IL IN KS KY LA MA MD ME ... WY
如果您更喜欢将输出作为字符值,请使用:
> split(as.character(key), 1:length(key) %% 2 == 0)
$`FALSE`
[1] "AL" "AZ" "CA" "CT" "FL" "HI" "IL" "IA" "KY" "ME" "MA" "MN" "MO" "NE" "NH"
[16] "NM" "NC" "OH" "OR" "RI" "SD" "TX" "VT" "WA" "WI"
$`TRUE`
[1] "AK" "AR" "CO" "DE" "GA" "ID" "IN" "KS" "LA" "MD" "MI" "MS" "MT" "NV" "NJ"
[16] "NY" "ND" "OK" "PA" "SC" "TN" "UT" "VA" "WV" "WY"
更新
如果您更喜欢单独的向量而不是列表,请尝试:
stOdds <- key[1:length(key) %% 2 == 1]
stEvens <- key[1:length(key) %% 2 == 0]