Home > Net >  R Access first element of the list while using loop and append it into a vector
R Access first element of the list while using loop and append it into a vector

Time:05-31

I have a function that gives results as shown.

List of 3
 $ D1: num 0.0509
 $ D2: num 0.0536
 $ D : num 0.0523

I want to access the first element of the list, and put all the values in a vector. It loops through the data in the following way. Vector1 and Vector2 have around 100 data.

A sample of data

vector1=c(1213, 57683, 74466, 44419, 17481, 3403, 42252, 7045,29445, 15004, 21337, 1892, 21861, 238, 26574, 17579)

vector2=c(3185, 29692, 12570, 26081, 4992, 1659, 16592, 1748, 37583, 6751, 10188, 355, 8116, 9, 5064, 1846)

It loops through the data in the following way.

w<-2
ab <- c()
for (i in w:length(vector1)){
  pred[[count]] <- vector1[(i-w 1):i]
  obs[[count]] <- vector2[(i-w 1):i]
  
  a1 <- pred[count]
  a2<- obs[count]
  count = count   1
  klvalue(unlist(a1),unlist(a2))
  a1 <- list()
  a2<- list()
  kldta<-append(klvalue,ab) 
}

The function is as shown

klvalue<- function(a,b){kl.dist(a, b, base = exp(1))
  }      #kl.dist is from library(seewave)

I know I can access the data in the last by doing klvalue[[1]] but I'm not really sure how to do it in a loop.

CodePudding user response:

I may have misunderstood, but is this your intended outcome?

#install.packages("seewave")
library(seewave)

klvalue<- function(a,b){kl.dist(a, b, base = exp(1))
}      #kl.dist is from library(seewave)

vector1=c(1213, 57683, 74466, 44419, 17481, 3403, 42252, 7045,29445, 15004, 21337, 1892, 21861, 238, 26574, 17579)
vector2=c(3185, 29692, 12570, 26081, 4992, 1659, 16592, 1748, 37583, 6751, 10188, 355, 8116, 9, 5064, 1846)

w<-2
ab <- list()
pred <- list()
obs <- list()
count <- 1
kldta <- list()

for (i in w:length(vector1)){
  pred[[count]] <- vector1[(i-w 1):i]
  obs[[count]] <- vector2[(i-w 1):i]
  
  a1 <- pred[count]
  a2 <- obs[count]
  count <- count   1
  klval <- klvalue(unlist(a1),unlist(a2))
  kldta[i] <- klval[[1]]
}

kldta_final <- unlist(kldta)
kldta_final
#>  [1] 0.0475256543 0.1523148191 0.1896899344 0.0468433690 0.0219116189
#>  [6] 0.0017162112 0.0115640592 0.1471657288 0.1053351614 0.0004260342
#> [11] 0.0253701967 0.0141622162 0.0148801420 0.0072153100 0.0403388718

Created on 2022-05-31 by the reprex package (v2.0.1)

  • Related