R 使用seq向量
我想在datatable中创建一个列,其中包含从起始向量到结束向量的所有整数的列表 有没有办法使用seq vectorwise?比如:R 使用seq向量,r,data.table,vectorization,seq,R,Data.table,Vectorization,Seq,我想在datatable中创建一个列,其中包含从起始向量到结束向量的所有整数的列表 有没有办法使用seq vectorwise?比如: library(data.table) Startpoints <- seq(1,11,5) Endpoints <- seq(5,15,5) DT <- data.table(Startpoints, Endpoints) DT[, sequences := seq(Startpoints, Endpoints, 1)] 更一般的
library(data.table)
Startpoints <- seq(1,11,5)
Endpoints <- seq(5,15,5)
DT <- data.table(Startpoints, Endpoints)
DT[, sequences := seq(Startpoints, Endpoints, 1)]
更一般的问题是:我想没有简单的方法将函数转换为它的向量化版本?
我仍然不完全理解vectorvariable何时表示一行中的单个值,以及当用作函数参数时,它何时表示其完整向量。您可以简单地使用Map:
当您试图将一个函数应用于多个向量的对应元素时,或者在您的case列中,它非常有用
DT[, .(seq = paste0(Startpoints:Endpoints, collapse = ",")),
by = c("Startpoints", "Endpoints")]
# Startpoints Endpoints seq
#1: 1 5 1,2,3,4,5
#2: 6 10 6,7,8,9,10
#3: 11 15 11,12,13,14,15
@弗兰克,谢谢你。。。我不知道这个函数。我刚刚和toString一起跑步,是的,还是一样的
DT[,sequences := Map(":", Startpoints, Endpoints)]
# Startpoints Endpoints sequences
#1: 1 5 1,2,3,4,5
#2: 6 10 6, 7, 8, 9,10
#3: 11 15 11,12,13,14,15
DT[, .(seq = paste0(Startpoints:Endpoints, collapse = ",")),
by = c("Startpoints", "Endpoints")]
# Startpoints Endpoints seq
#1: 1 5 1,2,3,4,5
#2: 6 10 6,7,8,9,10
#3: 11 15 11,12,13,14,15
library(dplyr)
DT %>% group_by(Startpoints, Endpoints) %>% mutate(seq = paste0(Startpoints:Endpoints, collapse = ","))
# Startpoints Endpoints seq
#1 1 5 1,2,3,4,5
#2 6 10 6,7,8,9,10
#3 11 15 11,12,13,14,15