-1

I want to separate a data of the form: " Score Card 45" into the form "score card" "45" i.e . I want to separate on the basis of type of data.

Can anyone please help me with it?

Another eg. : "Data type 45tr43" into "Data type" "45tr43"

zx8754
  • 42,109
  • 10
  • 93
  • 154
  • Could you provide more example rows? Looks like standard space separated text file that could be imported as `read.table("myFile.txt", sep = " ")` – zx8754 Sep 12 '19 at 10:43

2 Answers2

2

You might find it satisfactory to just use strsplit here, for a base R option:

input <- "Data type 45tr43"
parts <- strsplit(input, "(?<=\\D) (?=\\d)", perl=TRUE)
parts

[1] "Data type" "45tr43"

This assumes a splitting logic of a split on a space character which borders on the left with a non-digit, and on the right with a digit.

Tim Biegeleisen
  • 387,723
  • 20
  • 200
  • 263
0

You can use regexpr to find the first numeric and split the string at this position using substr. To remove spaces at the begin or end you can use trimws and in case you want only lower case in the output use tolower.

x  <- " Score Card 45"
i <- regexpr("\\d", x)
trimws(c(substr(x, 1, i-1), substring(x, i)))
#[1] "Score Card" "45"
trimws(substring(x, c(1,i), c(i-1,nchar(x))))
#[1] "Score Card" "45"
tolower(trimws(c(substr(x, 1, i-1), substring(x, i))))
#[1] "score card" "45"

x  <- "Data type 45tr43"
i <- regexpr("\\d", x)
trimws(c(substr(x, 1, i-1), substring(x, i)))
#[1] "Data type" "45tr43"
GKi
  • 20,626
  • 1
  • 11
  • 24