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

时间:2019-02-19 16:31:09

标签: r list loops

I Answer_vector应该等于sample_lengths,但实际上不是。我的代码输出如下:

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

[1] 31 33 36 40 34 30 39 38 37 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

1 个答案:

答案 0 :(得分:1)

以下是使用for循环,sapply和lapply的示例。所有结果都与sample_lengths向量中的值匹配。

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