简体   繁体   English

如何在 R 中使用 for 循环成对显示数字

[英]How to display numbers in pairs using for loops in R

I am trying to use for loop for my R shiny app which is more complex than just displaying the numbers and characters.我正在尝试为我的 R shiny 应用程序使用 for 循环,这比仅显示数字和字符更复杂。 Hence, I have written a much simpler version here.因此,我在这里写了一个更简单的版本。 Does anyone know how to display the following output using for loop?有谁知道如何使用 for 循环显示以下 output ?

"1,a"
"2,b"
"3,c"

So I have tried using the codes below:所以我尝试使用以下代码:

for(i in 1:3) {
  for(j in c("a","b","c")) {
    
    print(paste(i,j,sep = ","))
  }}

However, it produces this output:但是,它会产生这个 output:

[1] "1,a"
[1] "1,b"
[1] "1,c"
[1] "2,a"
[1] "2,b"
[1] "2,c"
[1] "3,a"
[1] "3,b"
[1] "3,c"

Can anyone help me with this?谁能帮我这个? Thanks!谢谢!

You probably only need one index i .您可能只需要一个索引i

for(i in 1:3) {
  print(paste(i, c("a","b","c")[i], sep = ","))
}
# [1] "1,a"
# [1] "2,b"
# [1] "3,c"

Unless you have a specific reason to be using one this is not a task best accomplished with a for loop.除非您有特定的理由要使用它,否则这不是使用 for 循环最好完成的任务。 You can take advantage of the fact that paste is vectorised and do this:您可以利用paste是矢量化的事实并执行以下操作:

paste(1:3, letters[1:3], sep = ",")

The sep argument to the paste function permits you to stitch together 2 vectors with a given string. paste function 的sep参数允许您使用给定的字符串将 2 个向量拼接在一起。

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

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