【发布时间】:2020-10-11 19:06:58
【问题描述】:
我有一个长度可能为 N 的向量。例如
x <- c(298, 307, 347, 374, 416)
我想为每对向量生成数字序列,如下所示:
298:307
308:347
348:374
375:416
并将其放入数据框中:
temp_df <- data.frame(i = c(298:307, 308:347, 348:374, 375:416),
j = c(rep(1, length(298:307)), rep(2, length(308:347)),
rep(3, length(348:374)), rep(4, length(375:416))))
我需要编写一个函数,它可以采用任意长度的向量并生成temp_df
temp_func <- function(my.vec){
temp.length <- length(my.vec) - 1
temp_list <- list()
for(j in 1:temp.length){
jk <- j + 1
if(j == 1){
temp_list[[j]] <-
data.frame(i = my.vec[j]:my.vec[jk],
j = j)
} else {
temp_list[[j]] <- data.frame(i = (my.vec[j] + 1):my.vec[jk],
j = j)
}
}
test <- do.call('rbind', temp_list)
return(test)
}
temp_func(x)
在 R 中是否有更快的方法来执行此操作?
【问题讨论】: