【发布时间】:2017-06-21 18:27:12
【问题描述】:
假设我有两个向量。
a <- c(1,5)
b <- c(2,3,4,6)
我想从这两个向量中创建一个向量,使得“a”中新向量中的位置为红色,“b”为蓝色,结果
c <- c('red','blue','blue','blue','red','blue')
我认为使用 rep 可能会有所帮助,但例如基于 a 和 b 的 rep 中的某种 ifelse?
【问题讨论】:
标签: r
假设我有两个向量。
a <- c(1,5)
b <- c(2,3,4,6)
我想从这两个向量中创建一个向量,使得“a”中新向量中的位置为红色,“b”为蓝色,结果
c <- c('red','blue','blue','blue','red','blue')
我认为使用 rep 可能会有所帮助,但例如基于 a 和 b 的 rep 中的某种 ifelse?
【问题讨论】:
标签: r
怎么样
cols <- rep(NA,length(a)+length(b))
cols[a] <- "red"
cols[b] <- "blue"
cols
# [1] "red" "blue" "blue" "blue" "red" "blue"
【讨论】:
这是stack 的选项。在list 和mget、stack 中获取vector 对象以创建data.frame、transform 的“ind”列到factor 和labels 为“红色”、“蓝色” ,在ordering 'values' 之后获取'ind'。
d1 <- transform(stack(mget(c('a', 'b'))), ind = factor(ind, labels = c('red', 'blue')))
as.character(d1$ind[order(d1$values)])
#[1] "red" "blue" "blue" "blue" "red" "blue"
正如@Frank 所说,使用这种方法,可以sorted out 2 个以上的向量
【讨论】:
与@MattTyers 简洁的解决方案相比,可能是更通用的解决方案:
cols <- sort(c(a,b))
cols[cols %in% a] <- "red"
cols[cols %in% b] <- "blue"
cols
# [1] "red" "blue" "blue" "blue" "red" "blue"
【讨论】: