if 语句在 for 循环中被忽略

J.S*_*ree 1 for-loop if-statement r

我正在编写一个基本的 for 循环,其中除最后一行之外的所有输出都应该相同。然而,即使条件是 ,我的 if 语句仍然被忽略TRUE

test_string <- c("test", "test2", "test3")

i <- 1
for(i in length(test_string)) {
  answer <- if(i < length(test_string)) {
    paste0("This is not the last '%", test_string, "%'")

  } else{
    paste0("This IS the LAST '%", test_string, "%'")
  }
  i <- i+1
}

#> [1] "This IS the LAST '%test%'"  "This IS the LAST '%test2%'"
#> [3] "This IS the LAST '%test3%'"
Run Code Online (Sandbox Code Playgroud)

小智 5

尝试将 seq_along() 添加到第一行。像这样:

test_string <- c("test", "test2", "test3")

for(i in seq_along(test_string)) {
  answer <- if(i < length(test_string)) {
    paste0("This is not the last '%", test_string[i], "%'")
  } else{
    paste0("This IS the LAST '%", test_string[i], "%'")
  }
  print(answer)
}
#[1] "This is not the last '%test%'"
#[1] "This is not the last '%test2%'"
#[1] "This IS the LAST '%test3%'"
Run Code Online (Sandbox Code Playgroud)

要将输出存储为变量:

test_string <- c("test", "test2", "test3")
answers <- c()

for(i in seq_along(test_string)) {
  answer <- if(i < length(test_string)) {
    paste0("This is not the last '%", test_string[i], "%'")
  } else{
    paste0("This IS the LAST '%", test_string[i], "%'")
  }
  answers <- c(answers, answer)
}

# View the results
answers
Run Code Online (Sandbox Code Playgroud)