道歉,因为我不知道该怎么说这个问题。假设有两个向量
v <- c("a","a","a","a",'b','b')
color <- c("red","yellow")
没有手动为每个独特元素指定颜色
final.color <- c("red","red","red","red","red","yellow","yellow")
如何自动创建此向量?
感谢。
答案 0 :(得分:0)
首先,我们在v
中找到唯一元素的数量,然后使用rep
重新创建final.color
v <- c("a","a","a","a",'b','b')
color <- c("red","yellow")
final.color <- c("red","red","red","red","yellow","yellow")
# find number of unique elements in a vector
n_unique <- c(table(v))
# create color from n_unique
tmp <- c(rep(color[1], n_unique[1]), rep(color[2], n_unique[2]))
tmp
#> [1] "red" "red" "red" "red" "yellow" "yellow"
identical(final.color, tmp)
#> [1] TRUE
由reprex package(v0.2.0)创建于2018-03-14。