Lennon Lee
Lennon Lee

Reputation: 244

r for loop only returning the last element

I have my list:

ll<-list(list(rt=c(1,2),it=c(3,4)),
         list(rt=c(5,6),it=c(7,8)),
         list(rt=c(9,10),it=c(11,12))
         )

I want to extract every element in the list and build a two columns dataframe by for loop, and I try:

testf<-function(x){
  null.d<-data.frame()
  for(i in length(x)){
    rtime<-x[[i]]$rt
    intensity<-x[[i]]$it
    dd<-data.frame(rtime,intensity)
    dd$ID<-i
    dd<-rbind(null.d,dd)
  }
  dd
}

test<-testf(ll)
> test
  rtime intensity ID
1     9        11  3
2    10        12  3

As shown, only the last element was exported, I have searched several similar questions but I am still unable to sovle my problem, may I know what's the problem?

Upvotes: 0

Views: 1056

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

Try using dplyr::bind_rows :

dplyr::bind_rows(ll, .id = 'ID')

# A tibble: 6 x 3
#  ID       rt    it
#  <chr> <dbl> <dbl>
#1 1         1     3
#2 1         2     4
#3 2         5     7
#4 2         6     8
#5 3         9    11
#6 3        10    12

It would work the same with data.table::rbindlist.

data.table::rbindlist(ll, idcol = 'ID')

If I had to use a for loop I would do it as :

testf<-function(x){

  result <- vector('list', length(x))
  for(i in seq_along(x)){
    rtime<-x[[i]]$rt
    intensity<-x[[i]]$it
    result[[i]] <- data.frame(rtime, intensity, ID = i)
  }
  do.call(rbind, result)
}
test  <- testf(ll)

Upvotes: 2

Related Questions