如何在R中分隔列表的输出

时间:2017-12-25 07:23:24

标签: r

我有一个返回列表列表的函数。我想分开列表的结果。第二个元素的第一个元素。 这是一个例子:

x1 <- replicate(4,0.5)
x2 <- replicate(4,0.7)
x <- list(x1,x2)
y <- list(0.5,0.6,0.3,0.4)
myfu <- function(x,y){
  out <- list()
out$y <- lapply(1:4, function(i){lapply(1:2, function(j) y[[i]]*x[[j]])})
return(out)
}

此函数返回:

    $y
$y[[1]]
$y[[1]][[1]]
[1] 0.25 0.25 0.25 0.25

$y[[1]][[2]]
[1] 0.35 0.35 0.35 0.35


$y[[2]]
$y[[2]][[1]]
[1] 0.3 0.3 0.3 0.3

$y[[2]][[2]]
[1] 0.42 0.42 0.42 0.42


$y[[3]]
$y[[3]][[1]]
[1] 0.15 0.15 0.15 0.15

$y[[3]][[2]]
[1] 0.21 0.21 0.21 0.21


$y[[4]]
$y[[4]][[1]]
[1] 0.2 0.2 0.2 0.2

$y[[4]][[2]]
[1] 0.28 0.28 0.28 0.28

我的问题是,如何将所有y[[i]][[1]]与所有y[[i]][[2]]分开。也就是说,我希望得到这样的结果:

$y
$y[[1]]
$y[[1]][[1]]
[1] 0.25 0.25 0.25 0.25

$y[[2]]
$y[[2]][[1]]
[1] 0.3 0.3 0.3 0.3

$y[[3]]
$y[[3]][[1]]
[1] 0.15 0.15 0.15 0.15


$y[[4]]
$y[[4]][[1]]
[1] 0.2 0.2 0.2 0.2

和第二个元素相同。

2 个答案:

答案 0 :(得分:5)

我们可以使用# LISTENER.ORA Network Configuration File: D:\ORACLE\ORA8I\network\admin\listener.ora # Generated by Oracle configuration tools. LISTENER = (DESCRIPTION_LIST = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1)) ) (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = svrstn01)(PORT = 1521)) ) ) (DESCRIPTION = (PROTOCOL_STACK = (PRESENTATION = GIOP) (SESSION = RAW) ) (ADDRESS = (PROTOCOL = TCP)(HOST = svrstn01)(PORT = 2481)) ) ) SID_LIST_LISTENER = (SID_LIST = (SID_DESC = (SID_NAME = PLSExtProc) (ORACLE_HOME = D:\ORACLE\ORA8I) (PROGRAM = extproc) ) (SID_DESC = (GLOBAL_DBNAME = SITEEN) (ORACLE_HOME = D:\ORACLE\ORA8I) (SID_NAME = SITEEN) ) )

transpose

答案 1 :(得分:1)

您的问题可能妨碍您实施lapply功能。获得所需内容的最简单方法是稍微更改lapply功能。也就是说,

x1 <- replicate(4,0.5)
x2 <- replicate(4,0.7)
x <- list(x1,x2)
y <- list(0.5,0.6,0.3,0.4)
myfu <- function(x,y){
  out <- list()
  out$y <- lapply(1:2, function(i){lapply(1:4, function(j) y[[j]]*x[[i]])})

  return(out)
}

因此,输出是:

> myfu(x,y)
$y
$y[[1]]
$y[[1]][[1]]
[1] 0.25 0.25 0.25 0.25

$y[[1]][[2]]
[1] 0.3 0.3 0.3 0.3

$y[[1]][[3]]
[1] 0.15 0.15 0.15 0.15

$y[[1]][[4]]
[1] 0.2 0.2 0.2 0.2


$y[[2]]
$y[[2]][[1]]
[1] 0.35 0.35 0.35 0.35

$y[[2]][[2]]
[1] 0.42 0.42 0.42 0.42

$y[[2]][[3]]
[1] 0.21 0.21 0.21 0.21

$y[[2]][[4]]
[1] 0.28 0.28 0.28 0.28