r for循环只返回最后一个元素

r for循环只返回最后一个元素,r,for-loop,R,For Loop,我有我的清单: 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)) ) ll尝试使用dplyr::bind_rows: dplyr::bind_rows(ll, .id = 'ID') # A tibble: 6 x 3 # ID rt it # <chr> <d

我有我的清单:

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))
         )

ll尝试使用
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

如果我必须为
循环使用一个
,我会这样做:

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)

testf尝试使用
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

如果我必须为
循环使用一个
,我会这样做:

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)

testf太棒了,非常感谢。但是我可以请求帮助更正我的代码吗?我真的很困惑,希望知道如何使用for循环改进我的代码,再次感谢!1.您应该使用
for(i in 1:length(x))
而不是
length(x)
。2.您正在使用
dd在每次迭代中覆盖
dd
,这非常有用!非常感谢你!太棒了,非常感谢。但是我可以请求帮助更正我的代码吗?我真的很困惑,希望知道如何使用for循环改进我的代码,再次感谢!1.您应该使用
for(i in 1:length(x))
而不是
length(x)
。2.您正在使用
dd在每次迭代中覆盖
dd
,这非常有用!非常感谢你!