使用多列作为参数应用函数,函数返回data.frame

使用多列作为参数应用函数,函数返回data.frame,r,function,apply,R,Function,Apply,我试图应用一个函数,该函数使用数据帧的多列作为参数,并且该函数为每一行返回一个数据帧。我可以在这里使用for循环,但我想检查一下是否有其他方法可以做到这一点 这里提供了一个简单的例子。我原来的问题稍微复杂一点 DF1<-data.frame(start=seq(from=1, to=5, by=1),end=seq(from=10, to=14, by=1)) rep_fun <- function(x,y) { data.frame( A=seq(x, y)) #produc

我试图应用一个函数,该函数使用数据帧的多列作为参数,并且该函数为每一行返回一个数据帧。我可以在这里使用for循环,但我想检查一下是否有其他方法可以做到这一点

这里提供了一个简单的例子。我原来的问题稍微复杂一点

DF1<-data.frame(start=seq(from=1, to=5, by=1),end=seq(from=10, to=14, by=1))

rep_fun <- function(x,y)
{
  data.frame( A=seq(x, y)) #produces a sequence between x and y
}

DF2<-data.frame()
for (i in 1:nrow(DF1)){
  temp<-data.frame(rep_fun(DF1$start[i],DF1$end[i]))
 DF2<-rbind(temp,DF2) # this contains a dataframe that has a sequence between 'start' and 'end' for  each row in DF1 

}
1)lappy
nrow(DF1):1拆分
DF1
,使其以相反顺序出现,然后
lappy
覆盖该列表,并将其组件组合在一起。没有使用任何软件包

DF3 <- do.call("rbind", lapply(split(DF1, nrow(DF1):1), with, rep_fun(start, end)))
rownames(DF3) <- NULL

identical(DF2, DF3)
## [1] TRUE

我相信这是xy问题的一个例子。但这里有一种可能的方法:
as.vector(apply(DF1,1,函数(x)x[1]:x[2])
正如我所提到的,我原来的问题更复杂。我的原始问题中的rep_-fun等价物将返回一个多行多列的数据帧。诚实地说,反转不是一个要求,但很高兴发现这是可能的!选择3就是我要选择的。它比我原来问题中的For循环选项快3倍左右!
DF3 <- do.call("rbind", lapply(split(DF1, nrow(DF1):1), with, rep_fun(start, end)))
rownames(DF3) <- NULL

identical(DF2, DF3)
## [1] TRUE
fun <- function(x) with(x, rep_fun(start, end))
DF4 <- do.call("rbind", Map(fun, split(DF1, nrow(DF1):1), USE.NAMES = FALSE))

identical(DF4, DF2)
## [1] TRUE
DF5 <- do.call("rbind", with(DF1, rev(Map(rep_fun, start, end))))

identical(DF5, DF2)
## [1] TRUE