0

I'm given the following list of numbers: 42 35 50 43 48 62 31 36 44 39 55 48 and I can't use them in R if there isn't a comma between each one. I don't want to spend ages manually entering commas in between each number (sometimes I'm given hundreds of numbers at a time!) How do I add a comma between each number using R in RStudio?

I googled this question and tried every suggestion but nothing worked. I know nothing about coding and only learnt how to use R the past few weeks.

Matt
  • 3
  • 4

2 Answers2

0

normally it would be nice if you could provide code, not just blank numbers. It is hard to guess what you need exactly.

list_of_numbers <- list(42, 35, 50, 43, 48, 62, 31, 36, 44, 39, 55, 48)

paste(list_of_numbers, collapse = ", ")
[1] "42, 35, 50, 43, 48, 62, 31, 36, 44, 39, 55, 48"

Hope this help you.

DSGym
  • 2,539
  • 1
  • 4
  • 15
  • 1
    You could also do `toString(list_of_numbers)` as `toString` is a wrapper around `paste(..., collapse = ", ")` – markus May 31 '19 at 07:24
  • great, this website is so awesome. So many clever people with clever solutions :-) – DSGym May 31 '19 at 07:36
0

For a list :

l <- list(42,35,50,43,48,62,31,36,44,39,55,48)
paste(l, sep = "", collapse = ",")

For a string :

gsub(" ", ",", "42 35 50 43 48 62 31 36 44 39 55 48", fixed = TRUE)

You can use ctrl+find and replace space by , if you copy paste it.

Clemsang
  • 3,708
  • 1
  • 19
  • 32
  • Thank you so much. I guess it was obvious that I could use the ctrl+find and replace function, I was just too dumb to know! I wish I knew this in my test, I wouldn't have wasted half the test just placing commas between a hundred numbers. – Matt May 31 '19 at 08:27
  • Glad it helped ! I have faced the same problem several times. – Clemsang May 31 '19 at 08:43