How to create a vector of character strings using a loop?

落爺英雄遲暮 提交于 2019-12-07 15:17:22

问题


I am trying to create a vector of character strings in R using a loop, but am having some trouble. I'd appreciate any help anyone can offer.

The code I'm working with is a bit more detailed, but I've tried to code a reproducible example here which captures all the key bits:

vector1<-c(1,2,3,4,5,6,7,8,9,10)
vector2<-c(1,2,3,4,5,6,7,8,9,10)
thing<-character(10)


for(i in 1:10) {
  line1<-vector1[i]
  line2<-vector2[i]
  thing[i]<-cat(line1,line2,sep="\n") 
}

R then prints out the following:

1
1

Error in thing[i] <- cat(line1, line2, sep = "\n") : 
  replacement has length zero

What I'm trying to achieve is a character vector where each character is split over two lines, such that thing[1] is

1
1

and thing[2] is

2
2

and so on. Does anyone know how I could do this?


回答1:


cat prints to the screen, but it returns NULL- to concatenate to a new character vector, you need to use paste:

  thing[i]<-paste(line1,line2,sep="\n") 

For example in an interactive terminal:

> line1 = "hello"
> line2 = "world"
> paste(line1,line2,sep="\n") 
[1] "hello\nworld"
> ret <- cat(line1,line2,sep="\n") 
hello
world
> ret
NULL

Though note that in your case, the entire for loop could just be replaced with the more concise and efficient line:

thing <- paste(vector1, vector2, sep="\n")
#  [1] "1\n1"   "2\n2"   "3\n3"   "4\n4"   "5\n5"   "6\n6"   "7\n7"   "8\n8"  
#  [9] "9\n9"   "10\n10"


来源:https://stackoverflow.com/questions/14504914/how-to-create-a-vector-of-character-strings-using-a-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!