【发布时间】:2016-03-20 03:23:22
【问题描述】:
我的目标是将多个元素插入到不同位置的向量中。这是一个例子,后面跟着一些不起作用的试验。
w <- c( 1,3,2,4,2,3,2,4,5,7,9,3,2,4,2,5,7,4,2 )
u <- c( 3,7,9,12 )
o <- c( 10 , 20 , 30 , 40 )
我试过了:
append ( w , o , after = u )
# which adds the series one time in the first location of after
fun <- function (x) append ( w , o[[x]] , after = u[[x]] )
lapply ( seq ( length ( u )) , fun )
# which adds one element to the list each time for a new vector producing a number of vectors
for (i in length(o)) {
append ( w , o[[i]] , after = u[[i]] )
}
# which basically does nothing
期望的输出
1,3,2,10,4,2,3,2,20,4,5,30,7,9,3,40,2,4,2,5,7,4,2
有没有办法在每个特定位置一次插入一个元素?我已经看到几个问题解决了单个元素的附加基本问题,其中一个位置或两个元素要添加到同一位置,而不是多个元素要添加到向量中的多个位置。
【问题讨论】:
-
刚刚被提示找到一个解决方案,因为我忘记在问题中为循环命名。但是,根据许多建议的解决方案,矢量化应该更快。
标签: r