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"
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"
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.
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"