用 for 循环进行更多迭代
迭代不只是用于读取文件;它也可以对对象执行其他操作。首先,您将尝试用 for 循环进行迭代。
您将把列表中的每个元素转换为数值数据类型,然后再放回到同一个列表的同一个元素位置。
在本练习中,您会使用 for 循环对 list_of_df 进行迭代。list_of_df 是由字符向量组成的列表,但这些字符其实是数字!为了进行数学运算,您需要把字符向量转换为数值类型;可以使用 R 基础函数 as.numeric() 来完成。
本练习是课程的一部分
使用 purrr 掌握函数式编程基础
练习说明
- 检查
list_of_df第一个元素的类别类型。 - 编写一个 for 循环,依次取出
list_of_df的每个元素,用as.numeric()将其转换为数值型,并将结果放回list_of_df中相同的位置。 - 再次检查
list_of_df第一个元素的类别类型。 - 打印
list_of_df。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# 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
___