0

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

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! It works with some fiddling around, I still had to change some vars. Some are apparently numeric and some a strings (or character vars). This dataset is horrible. Could you show how to extract the result from a numeric variable? I have a lot of variables that require this procedure
@fleems the above answer is numeric. (It's a data frame with numeric columns). What do you mean by "extract the result"? In what format?
I meant if the starting variable wasn't a string, but a numeric array of numbers (as in a data frame). So from a original numeric variable, that has 5 data points, extract the A1 to A5 variables chronologically.
1

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.