2016-04-16 13 views
-1

私はベクトルvを持っているとしましょう。条件でベクトルを作成

v <- c("A", "B", "C", "C", "B", "A", "A", "C", "A") 

今、私はこれらの条件を以下の同等のベクトルv'たいと思います:あなたは要素を検索、参照ベクトルを使用することができ

if v[i]=='A' 
    then v'[i]='Q' 
else v'[i]='P' 

答えて

2
v1 <- c("A","B","C","C","B","A","A","C","A") 
v2 <- rep("P", length(v1)) 
v2[v1 == "A"] <- "Q" 
#> v2 
#[1] "Q" "P" "P" "P" "P" "Q" "Q" "P" "Q" 

それとも

v2 <- ifelse(v1=="A","Q","P") 
#[1] "Q" "P" "P" "P" "P" "Q" "Q" "P" "Q" 
2

vAではありません。

v <- c("A","B","C","C","B","A","A","C","A") 

c("Q", "P")[(v != "A") + 1L] 
# [1] "Q" "P" "P" "P" "P" "Q" "Q" "P" "Q" 
関連する問題