假设我有以下列表清单。
tau1 <- rnorm(10,0,1)
tau2 <- rnorm(10,0,1)
tau <- list(tau1, tau2)
tau
tau3 <- rnorm(10, 0,1)
tau4 <- rnorm(10,0,1)
tau5 <- list(tau3, tau4)
tau5
然后,我的以下函数返回一个列表列表。
Tau <- list(tau, tau5)
myfun <- function(Tau){
m <- length(Tau[[1]])
tau1 <- lapply(1:m, function(i) (Tau[[1]][[i]]+tau[[2]][[i]]))
Tau1 <- lapply(1:m, function(i) Tau[[1]][[i]]/ (Reduce("+", tau1[[i]])))
Tau2 <- lapply(1:m, function(i) Tau[[2]][[i]]/ (Reduce("+", tau1[[i]])))
w1 <- lapply(1:m, function(i) mean(Tau1[[i]]))
w2 <- lapply(1:m, function(i) mean(Tau2[[i]]))
w <- list(w1, w2)
return(w)
}
输出如下:
> myfun(Tau)
[[1]]
[[1]][[1]]
[1] -0.4593304
[[1]][[2]]
[1] -0.302662
[[2]]
[[2]][[1]]
[1] 1.45933
[[2]][[2]]
[1] 1.302662
我希望输出如下:
> myfun(Tau)
[[1]]
[1] -0.4593304. -0.302662
[[2]]
[1] 1.45933 1.302662
请帮忙吗?
答案 0 :(得分:0)
一种方法是将unlist添加到您的函数中:
myfun <- function(Tau){
m <- length(Tau[[1]])
tau1 <- lapply(1:m, function(i) (tau[[1]][[i]]+tau[[2]][[i]]))
Tau1 <- lapply(1:m, function(i) tau[[1]][[i]]/ (Reduce("+", tau1[[i]])))
Tau2 <- lapply(1:m, function(i) tau[[2]][[i]]/ (Reduce("+", tau1[[i]])))
w1 <- unlist(lapply(1:m, function(i) mean(Tau1[[i]])))
w2 <- unlist(lapply(1:m, function(i) mean(Tau2[[i]])))
w <- list(w1, w2)
return(w)
}
myfun(Tau) #the original version
#output
[[1]]
[1] -0.5441523 0.6246206
[[2]]
[1] 1.5441523 0.3753794
另一个是做:
z <- myfun(Tau) #the original function
lapply(z, unlist)
#output
[[1]]
[1] -0.5441523 0.6246206
[[2]]
[1] 1.5441523 0.3753794
答案 1 :(得分:0)
您是否在unlist
选项关闭的情况下尝试recursive
?希望这会奏效:
> tau2 <- unlist(Tau,recursive=FALSE)
> tau2
[[1]]
[1] -0.37723765 0.09761946 1.63874465 -0.87559247 0.12176000 1.36213066 -0.23462109 -1.05338281
[9] -0.86978361 -0.39012703
[[2]]
[1] -0.84735007 -0.26063939 -0.41441971 -0.18305080 0.40705610 0.62463313 1.67820574 -0.06869365
[9] -0.32083991 1.47100572
[[3]]
[1] 1.70432940 0.04324404 -0.33265732 -1.82223542 1.41126240 -0.83758243 -1.12376279 3.04376589
[9] 0.23502131 -0.03325861
[[4]]
[1] -2.73221952 -0.09979059 0.97603173 0.41386892 0.91232216 1.98373220 1.16910851 -0.50873702
[9] 0.70418018 -0.19841627