Get startedGet started for free

More iteration with for loops

Iteration isn't just for reading in files though; iteration can be used to perform other actions on objects. First, you will try iterating with a for loop.

You're going to change each element of a list into a numeric data type and then put it back into the same element in the same list.

For this exercise, you will iterate using a for loop that takes list_of_df, which is a list of character vector, but the characters are actually numbers! You need to change the character vectors to numeric so that you can perform mathematical operations on them; you can use the base R function, as.numeric() to do that.

This exercise is part of the course

Foundations of Functional Programming with purrr

View Course

Exercise instructions

  • Check the class type of the first element of list_of_df.
  • Build a for loop that takes each element of list_of_df, changes it into numeric data with as.numeric(), and adds it back into the same element of list_of_df.
  • Check the class type of the first element of list_of_df.
  • Print list_of_df.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Check the class type of the first element
class(___[[___]])

# Change each element from a character to a number
for(i in seq_along(list_of_df)){
    ___[[___]] <- as.numeric(___[[___]])
}

# Check the class type of the first element
class(___[[___]])

# Print out the list
___
Edit and Run Code