编写for循环以查找列表中向量的长度

编写for循环以查找列表中向量的长度,r,list,loops,R,List,Loops,答案向量应该等于样本长度,但它不是。我的代码输出如下: [1] 32 35 39 44 39 36 46 42 46 [1] 31 33 36 40 34 30 39 38 32 35 set.seed(42) sample_lengths <- sample(30:40) list1 <- lapply(sample_lengths, sample) # create an empty vector for answers Answer_vector <- rep(NA,

答案向量应该等于样本长度,但它不是。我的代码输出如下:

[1] 32 35 39 44 39 36 46 42 46

[1] 31 33 36 40 34 30 39 38 32 35

set.seed(42)
sample_lengths <- sample(30:40)
list1 <- lapply(sample_lengths, sample) 

# create an empty vector for answers
Answer_vector <- rep(NA, length(list1))

# loop over list and find lengths
list1 <- lapply(sample_lengths, sample)

for (i in 1:length(list1)) {
      Answer_vector[i]<-sample_lengths[i]+i
    }
Answer_vector
sample_lengths

下面是使用for-loop、sapply和lappy的示例。所有结果都与样本长度向量中的值匹配


为什么不用长度?我不明白这个问题。1.请使用set.seed,以便我们可以复制您的示例数据。2.也许用长度1?你的问题没有意义。在循环中,将i添加到“sample_length”的第i个条目中,并将其存储在Answer_向量中,因此它们不相等也就不足为奇了sappylist1,length?我想使用循环与apply函数进行比较。
set.seed(42)
sample_lengths <- sample(30:40)
list1 <- lapply(sample_lengths, sample) 

# create an empty vector for answers
Answer_vector <- integer()

# Length of each vector using a loop
for (i in 1:length(list1)) {
  Answer_vector[i] <- length(list1[[i]])
}

# Length of each vector using sapply
sapply.answer.vector <- sapply(list1, length)


# Length of each vector using lapply
lapply.answer.vector <- unlist(lapply(list1, length))