2012-07-30 103 views
1

我有數值向量的列表NList迭代數值向量列表中的

[[1]] 
[1] 1959 9 4 62 

[[2]] 
[1] 2280 2 13 

[[3]] 
[1] 15 4 13 

[[4]] 
[1] 2902 178 13 

,結構等

list(c(1959, 13), c(2280, 178, 13), c(2612, 178, 13), c(2902, 
178, 13), c(2389, 178, 13), c(216, 736, 13), c(2337, 178, 13), 
    c(2639, 2126, 13), c(2924, 676, 178, 13), c(2416, 674, 178, 
    13), c(2223, 13), c(842, 178, 13), c(2618, 1570, 178, 13), 
    c(854, 178, 13), c(1847, 178, 13), c(2529, 178, 13), c(511, 
    178, 13), c(2221, 736, 13), c(415, 674, 178, 13), c(2438, 
    178, 13), c(2127, 178, 13), c(1910, 2126, 13), c(1904, 674, 
    178, 13), c(2310, 674, 178, 13), c(1732, 178, 13), c(1843, 
    178, 13), c(2539, 178, 13), c(1572, 676, 178, 13), c(1616, 
    876, 13).....) 

欲迭代數值向量在此列表中,我想做點什麼:

sum<- 0 
    index<-1 
    list1 <- apply(NList,1,function (i){ 
    #I want to get each of the numeric vector here 
    row <- NList[i] 

    #then I want to iterate the numeric vector for some calculation. 
    #I am expecting, for [[1]], I get f(1959,9)+f(9,4)+f(4,62), in which f is my customized function, below I use a simple multiple as example 
    for (j in (1:(length(row)-1))) 
    { 
    origin <- row[j] 
    dest <- row[j+1] 
    #a simple calculation example...I am expecting an array of sum which is the calculation result 
    sum[index] <- sum[index] + origin*dest 
    } 
    index <- index+1 

    }) 

但它不起作用並返回:

dim(X) must have a positive length 

的lapply是不是爲我工作,並返回總和爲0 ...

listR1 <- lapply(NList,function (i){ 
    row <- i 
    for (j in 1:length(row)) 
    {origin <- row[j] 
    dest <- row[j+1] 
    sum[index] <- sum[index] + origin*dest 
    } 

    }) 

我錯過了什麼?我怎樣才能做到這一點?
謝謝!

+3

讓一個名爲'list'的對象變得非常混亂e list()是一個函數。 – Seth 2012-07-30 20:31:42

+1

要'申請'在你想要的'?lapply'列表上。除此之外,我無法效仿你的榜樣... – Justin 2012-07-30 20:31:42

+3

你能告訴我們更多關於你喜歡的結果,而不是如何去做。你的方法看起來非常不像R。 – 2012-07-30 20:31:59

回答

3

我把你的應用語句中的函數看得更近了一點。

f=function(Row) 
    { 
    Sum<- 0 
     for (j in 1:(length(Row)-1) ) 
     { 
      Sum<- j + Row[j]*Row[j+1] 
     } 
    Sum # returns the Sum 
    } 

然後我可以申請的功能,每行有:

list1 <- lapply(NList,f) 
+0

謝謝!真的行。我想知道爲什麼我的方法不起作用。或者你能否指點我一些關於R中矢量化的材料? – Seen 2012-07-30 21:02:32

+2

我最喜歡的矢量化來源是http://www.burns-stat.com/pages/Tutor/R_inferno.pdf圈3。 – Seth 2012-07-30 21:15:53

+0

非常感謝您的參考。 – Seen 2012-07-31 03:56:27

2

好了,所以這段代碼將工作:

f=function(a,b) sum(a,b) 

test.func=function (i){ 
    for (j in 1:(length(i)-1)) 
    ret.val[j]=f(i[j],i[j+1]) 
    ret.val 
} 

# Use lapply for a list. 
lapply(NList,test.func) 

或者你可以做一個行:

lapply(NList,apply(seq_along(i)[-length(i)],function(x) f(i[x],i[x+1]))) 
+0

它看起來非常好...非常感謝您的答案。 – Seen 2012-07-30 21:03:50