假设我有一个向量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'
答案 0 :(得分: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"
答案 1 :(得分:2)
您可以使用查找向量,搜索v
不是A
的元素。
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"