for循环遍历R中的一个tibble
for loop over a tibble in R
在 RSTUDIO 上工作
所以,我有 titanic.csv 的基本数据集,其中第五列是年龄。
我想要做的是将 年龄 的整列存储在一个变量中,并在其上 运行 一个 for 循环。
当我尝试这样做时,它显示该变量是一个 tibble。
我用来读取 csv 文件并将其存储在名为 tata 的变量中的命令是:
tata <- read_csv("titanic.csv")
csv 文件与 .r 文件位于同一目录中,因此在这里读取文件没有任何问题。
获取变量age的第五列x
x <- tata[,5]
当我打印 x 时,我在控制台中得到了这个:
然后我尝试获取多行打印语句,上面写着:第 n 个人的年龄:(the variable_value)
for (age in x) {
print(paste("The", n , "th person has age:", age))
n = n + 1
}
我得到的输出为:
[1] "The 1 th person has age 22" "The 1 th person has age 38"
[3] "The 1 th person has age 26" "The 1 th person has age 35"
[5] "The 1 th person has age 35" "The 1 th person has age 27"
[7] "The 1 th person has age 54" "The 1 th person has age 2"
[9] "The 1 th person has age 27" "The 1 th person has age 14"
[11] "The 1 th person has age 4" "The 1 th person has age 58"
这一直持续到 887 行
我希望你明白我在这里需要什么。任何帮助将不胜感激。
由于您已将数据转换为 tibble
(即 read_csv
而不是 read.csv
),您需要调用
x <- tata$Age
而不是
x <- tata[, 5]
这是因为后者 returns 又是一个小问题,因此 paste(..., print(x))
的工作方式与您预期的不同。
附录
for 循环在 R 中通常不是一个好主意。看看 *apply
函数族或 purrr
包。
例如,
library(dplyr)
tata %>%
pull(Age) %>%
sapply(function(age) paste("Person is", age, "years old"))
在 R 中,你可以在没有循环的情况下完成大部分事情。
例如,这里你可以试试矢量化的paste
。
x <- unlist(x)
paste("The ", seq_along(x), "th person has age ", x)
或使用for
循环
for (i in seq_along(x)) {
cat("\nThe ", i, "th person has age ", x[i])
}
在 RSTUDIO 上工作
所以,我有 titanic.csv 的基本数据集,其中第五列是年龄。 我想要做的是将 年龄 的整列存储在一个变量中,并在其上 运行 一个 for 循环。 当我尝试这样做时,它显示该变量是一个 tibble。
我用来读取 csv 文件并将其存储在名为 tata 的变量中的命令是:
tata <- read_csv("titanic.csv")
csv 文件与 .r 文件位于同一目录中,因此在这里读取文件没有任何问题。
获取变量age的第五列x
x <- tata[,5]
当我打印 x 时,我在控制台中得到了这个:
然后我尝试获取多行打印语句,上面写着:第 n 个人的年龄:(the variable_value)
for (age in x) {
print(paste("The", n , "th person has age:", age))
n = n + 1
}
我得到的输出为:
[1] "The 1 th person has age 22" "The 1 th person has age 38"
[3] "The 1 th person has age 26" "The 1 th person has age 35"
[5] "The 1 th person has age 35" "The 1 th person has age 27"
[7] "The 1 th person has age 54" "The 1 th person has age 2"
[9] "The 1 th person has age 27" "The 1 th person has age 14"
[11] "The 1 th person has age 4" "The 1 th person has age 58"
这一直持续到 887 行
我希望你明白我在这里需要什么。任何帮助将不胜感激。
由于您已将数据转换为 tibble
(即 read_csv
而不是 read.csv
),您需要调用
x <- tata$Age
而不是
x <- tata[, 5]
这是因为后者 returns 又是一个小问题,因此 paste(..., print(x))
的工作方式与您预期的不同。
附录
for 循环在 R 中通常不是一个好主意。看看 *apply
函数族或 purrr
包。
例如,
library(dplyr)
tata %>%
pull(Age) %>%
sapply(function(age) paste("Person is", age, "years old"))
在 R 中,你可以在没有循环的情况下完成大部分事情。
例如,这里你可以试试矢量化的paste
。
x <- unlist(x)
paste("The ", seq_along(x), "th person has age ", x)
或使用for
循环
for (i in seq_along(x)) {
cat("\nThe ", i, "th person has age ", x[i])
}