如何返回包含向量和指定长度的列表的列表列表?

时间:2019-04-22 10:11:32

标签: r

我正在编写一个期望返回列表的函数(我将其命名为Layer)。在列表的每个元素中,应该有许多事物的列表(例如A,B,C,D),其中一些是向量(例如A和B),而另一些是列表(例如C和D) )。我想要的输出是:

> output = MyFunction(...)
> output
$Layer[[1]]
$Layer[[1]]A
  ...
$Layer[[1]]B
  ...
$Layer[[1]]C
  ...
$Layer[[1]]D
  ...

$Layer[[3]]
$Layer[[3]]A
  ...
$Layer[[3]]B
  ...
$Layer[[3]]C
  ...
$Layer[[3]]D

我尝试使用

Layer[[r]] = list(.....)

在我的职能中。 但是R将错误消息显示为:

attempt to select more than one element in integerOneIndex

现在我尝试以下代码



MyFunction = function(Data, Cost, Time, MaxTime, Crit)){

  Layer = list()  
...


  Layer[r] = list(A = A, B = B, C = C, D = D)

  }                                                   
return(list(Layer = Layer))
}                                

但是R将警告消息显示为:

number of items to replace is not a multiple of replacement length

因此,它给了我一个长度比我预期更长的列表,像这样:

> output = MyFunction(...)
> output
$Layer
$Layer[[1]]
$Layer[[1]][[1]]
[1] A
  ...
$Layer[[2]]
[1] B
  ...
$Layer[[3]]
[1] C
  ...
$Layer[[4]]
[1] D
  ...


$Layer[[17]][[1]]
[1] A
  ...
$Layer[[18]][[1]]
[1] B
  ...
$Layer[[19]][[1]]
[1] C
  ...
$Layer[[20]][[1]]
[1] D

由于A,B,C,D是不同类型的对象(向量和列表),并且它们具有不同的长度,因此我应该如何将所有对象放入返回的一个元素(第i层)中清单?

我的数据是

   A1 A2 A3 A4 A5 A6 A7 Class
1   A  A  A  A  A  A  A     T
2   A  B  B  B  B  B  B     F
3   A  A  B  A  B  B  B     F
4   B  B  B  D  B  A  D     T
5   B  A  A  B  A  B  B     F
6   B  A  C  C  B  B  C     F
7   C  A  B  D  A  A  D     F
8   C  B  A  A  B  A  A     F
9   B  A  B  A  A  A  A     T
10  A  A  B  D  A  B  D     T

Cost = c(5, 4, 7, 2, 8, 2, 6)     
Time = c(4, 2, 3, 10, 6, 5, 11)   

我的代码的简短版本如下:

MyFunction = function(Data, Cost, Time, MaxTime = 10){
  Ar = colnames(Data) 
  Layer = list()  
  current.layer = list(Node = list(rownames(Data)), Cost = 0, Time = 0)
  Layer[[1]] = current.layer
  AllNewNode = c() ; Done = c() ; Cost = c() ; Time = c() 
  for ( r in 1:ncol(Data)){
     Var = Ar[r]
     done = vector("list", nlevels(Data[,Var]))
     newNode = vector("list", nlevels(Data[,Var]))
     CostNi = c() ; TimeNi = c() 
 for (s in 1:nlevels(Data[,Var])){
               SS = subset(Data, Data[,Ar==Var] == levels(Data[,Var])[s])
               newNode[[s]] = rownames(SS)
               done[[s]] = c(Var)
               var = rep(1,ncol(Data))*(Ar==Var)
               CostNi[s] = current.layer$Cost + Cost[var==1]
               TimeNi[s] = current.layer$Time + Time[var==1]
             }     
   AllNewNode = c(AllNewNode, newNode)
   Done = c(Done, done)   
   Cost = c(Cost, CostNi) ; Time = c(Time, TimeNi)

  Layer[r] = list(Node = AllNewNode, Done = Done, Cost = Cost, Time = Time)

  }                                                   
return(list(Layer = Layer))
}                                



out = MyFunction(Data, Cost, Time, MaxTime = 10)

0 个答案:

没有答案