繁体   English   中英

for循环在R中的一个tibble上

[英]for loop over a tibble in R

在 RSTUDIO 上工作

所以,我有 Titanic.csv 的基本数据集,它的第五列是年龄。 我想要做的是将整个年龄列存储在一个变量中并在其上运行 for 循环。 当我尝试这样做时,它表明该变量是一个小标题。

我用来读取 csv 文件并将其存储在名为tata的变量中的命令是:

tata <- read_csv("titanic.csv")

csv文件是在同一目录中.R文件,所以读取文件没有任何问题在这里。

在变量x 中获取年龄的第五列

x <- tata[,5]

当我打印 x 我在控制台中得到这个:

控制台窗口

然后我尝试得到一个多行打印语句,上面写着:第n个人有年龄: (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]

这是因为后者再次返回一个小标题,因此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])
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM