kxb35
kxb35

Reputation: 41

Write a for loop to find the lengths of the vectors in a list

I The Answer_vector should equal sample_lengths, which it doesn't. My code outputs this:

[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

Upvotes: 0

Views: 256

Answers (1)

Matt Jewett
Matt Jewett

Reputation: 3379

Here are examples using a for loop, sapply, and lapply. All results match the values in the sample_lengths vector.

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

Upvotes: 1

Related Questions