我有一个这样的命名数字向量:
c(`1` = 2, `5` = 3, `6` = 1, `7` = 2, `8` = 1, `9` = 1)
#1 5 6 7 8 9 (names)
#2 3 1 2 1 1 (values)
我想扩展向量,以使名称形成整数序列,并用0
填充值。
这是我的预期输出:
c(`1` = 2, `2` = 0, `3` = 0, `4` = 0, `5` = 3, `6` = 1, `7` = 2, `8` = 1, `9` = 1)
#1 2 3 4 5 6 7 8 9
#2 0 0 0 3 1 2 1 1
有帮助吗? 谢谢
答案 0 :(得分:1)
这是我使用基于名称的索引的解决方案:
vec = c("1" = 2, "5" = 3, "6" = 1, "7" = 2, "8" = 1, "9" = 1)
newvec = double(9);
names(newvec) = 1:9
newvec[names(vec)] = vec;
newvec
# 1 2 3 4 5 6 7 8 9
# 2 0 0 0 3 1 2 1 1
答案 1 :(得分:0)
x <- c(2, 3, 1, 2, 1, 1)
names(x) <- c(1, 5, 6, 7, 8, 9) # original vector
y <- rep(0, 3)
names(y) <- 2:4 # to be added
append(x, y, 1) # insert y into x after position 1
# Result:
# 1 2 3 4 5 6 7 8 9
# 2 0 0 0 3 1 2 1 1