Home > Enterprise >  How to convert a single string array in to multiple variables
How to convert a single string array in to multiple variables

Time:12-09

Since I cannot convert a given data file to anything useful such as a .csv file, I want to extract multiple variables from a single string.

A string is labeled as A and has X points (somewhere between 10 and 17). The first point corresponds to 1 (as in A1) and the second to A2, et cetera. If there are only 10 numbers then max would be A10, if there are 17 then A17 is the max. I am not sure how to use dim().

How do I chronologically extract the numbers from my single string variable A in to multiple variables that are numbered A1:5 if there are 5 numbers in a given string?

A: 0.00 15.00 16.00 0.00 12.00

into

id   A1    A2     A3     A4    A5
001  0.00  15.00  16.00  0.00  12.00

CodePudding user response:

If your string is called string:

string <- "A: 0.00 15.00 16.00 0.00 12.00"

Then you could do something like:

sub(":", "", string) |>
  strsplit(' ') |>
  sapply(function(x) {
    setNames(as.numeric(x[-1]), paste0(x[1], seq_along(x[-1])))
  }) |> 
  t() |>
  as.data.frame()
#>   A1 A2 A3 A4 A5
#> 1  0 15 16  0 12

CodePudding user response:

Another option with read.table

out <- read.table(text = trimws(string, whitespace = ".*:\\s "), header = FALSE)
names(out) <- sub("V", substring(string, 1, 1), names(out))

-output

> out
  A1 A2 A3 A4 A5
1  0 15 16  0 12

data

string <- "A: 0.00 15.00 16.00 0.00 12.00"
  • Related