Having a dataframe like this:
data.frame(text = c("separate1: and: more","another 20: 42")
How is it possible to separate using the first : in every row? Example expected output
data.frame(text1 = c("separate1","another 20"), text2 = c("and: more","42")
In base you can use regexpr
to find the position of the first :
which can be used to extract substrings and trimws
to remove whitespaces.
x <- c("separate1: and: more","another 20: 42")
i <- regexpr(":", x)
data.frame(text1 = trimws(substr(x, 1, i-1)), text2 = trimws(substring(x, i+1)))
# text1 text2
#1 separate1 and: more
#2 another 20 42
library(reshape2)
df <- data.frame(text = c("separate1: and: more","another 20: 42")
colsplit(df$text, ":", c("text1", "text2"))
You can use str_split_fixed
from stringr
package which will by default split on the first delimiter, i.e.
stringr::str_split_fixed(d1$text, ':', 2)
# [,1] [,2]
#[1,] "separate1" " and: more"
#[2,] "another 20" " 42"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With