按条件创建矢量

时间:2016-04-16 20:41:37

标签: r vector

假设我有一个向量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 个答案:

答案 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"