[英]Add multiple columns to data.frame using a function that returns multiple outputs in dplyr
[英]Applying function using multiple columns as argument , function returns a data.frame
我试图应用一个函数,该函数使用一个数据框的多个列作为参数,并且该函数为每一行返回一个数据框。 我可以在这里使用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
}
我可以通过for循环获得的理想结果如下所示。 此处未显示所有行。 第1至10行显示了与DF1中第5行相对应的序列
> DF2
A
1 5
2 6
3 7
4 8
5 9
6 10
7 11
8 12
9 13
10 14
11 4
12 5
1)lapply拆分DF1
由nrow(DF1):1
,使得其以相反的顺序出来,然后lapply
在该列表和rbind
及其组件在一起。 不使用任何软件包。
DF3 <- do.call("rbind", lapply(split(DF1, nrow(DF1):1), with, rep_fun(start, end)))
rownames(DF3) <- NULL
identical(DF2, DF3)
## [1] TRUE
2)地图或此替代方法:
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
3)Map / rev像(2)一样使用Map
但是这次直接使用rep_fun
。 同样,它使用rev
在计算之后对输出进行排序,而不是在计算之前对split
进行排序。
DF5 <- do.call("rbind", with(DF1, rev(Map(rep_fun, start, end))))
identical(DF5, DF2)
## [1] TRUE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.