How to change a vector without comma?

I copy and paste a column vector in a table in my pdf e-textbook. So when it goes to my computer, it doesn't have comma in my R.

The data is:

49.0 50.2 50.5 48.5 47.5 44.5 28.0 31.5 34.5 35.0 38.0 38.5 15.0 17.0 20.5 29.5

How to make it a vector in R, such that c(49, 50.2,...)

There is probably a simpler way of doing this, but:

a <- "49.0 50.2 50.5 48.5 47.5 44.5 28.0 31.5 34.5 35.0 38.0 38.5 15.0 17.0 20.5 29.5"

b <- gsub("\\s", ", ", a)

c <- strsplit(b, ",")[[1]]

as.numeric(c)
[1] 49.0 50.2 50.5 48.5 47.5 44.5 28.0 31.5 34.5 35.0 38.0 38.5 15.0 17.0 20.5 29.5

2 Likes

There is also a stringr/piped approach, which works much the same as @williaml's answer:

vec = "49.0 50.2 50.5 48.5 47.5 44.5 28.0 31.5 34.5 35.0 38.0 38.5 15.0 17.0 20.5 29.5" |> 
  stringr::str_replace_all(" ", ", ") |> 
  stringr::str_split(pattern = ", ", simplify = T) |> 
  as.numeric()

If you encounter this situation a lot, you could even wrap it up in a function:

deparse_vector = function(vec, delim = " "){
  
  vec |> 
    stringr::str_replace_all(delim, ", ") |> 
    stringr::str_split(pattern = ", ", simplify = T) |> 
    as.numeric()
  
}

deparse_vector("49.0 50.2 50.5 48.5 47.5 44.5 28.0 31.5 34.5 35.0 38.0 38.5 15.0 17.0 20.5 29.5")
2 Likes

A third alternative is to use the {datapasta} package which provides an Rstudio add-in, that lets you paste a sequence like in your example as a vector by simply having the text in your computers clipboard and selecting the option from the Rstudio addins menu.

2 Likes

A non-R solution: open the file in a text editor (Microsoft Word for example) and replace all spaces with a comma and a space. Save as text (or comma separated values if that is an option. If saved as text, then go into Windows Explorer (or equivalent) and edit the file name to a .csv format. Then read as a csv file in R. Make sure to close your files before trying to read them in R.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.