我是R语言的新手.我遇到了需要在向量中的备用位置填充零的情况.例如:
v<-c(1,2,3,4,5,6,7,8,9,10)
Run Code Online (Sandbox Code Playgroud)
我需要新的矢量
0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0 10
Run Code Online (Sandbox Code Playgroud)
我尝试使用for循环填充零但我无法做到.
我相信有很多解决方案,但是
as.vector(rbind(0,v))
[1] 0 1 0 2 0 3 0 4 0 5 0 6 0 7 0 8 0 9 0 10
Run Code Online (Sandbox Code Playgroud)
会做的.
几种方法
创建一个零向量,然后替换正确的索引
x1 <- rep(0, length(x)*2)
x1[seq(2,20,by=2)] <- x
Run Code Online (Sandbox Code Playgroud)
或使用Map和c
unlist(Map(c,0,x))
Run Code Online (Sandbox Code Playgroud)