Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Separate rows into columns using the first split character

Tags:

r

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")
like image 831
Nathalie Avatar asked Feb 10 '20 14:02

Nathalie


3 Answers

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
like image 162
GKi Avatar answered Nov 13 '22 09:11

GKi


library(reshape2)

df <- data.frame(text = c("separate1: and: more","another 20: 42")

colsplit(df$text, ":", c("text1", "text2"))
like image 20
Georgery Avatar answered Nov 13 '22 09:11

Georgery


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"       
like image 25
Sotos Avatar answered Nov 13 '22 10:11

Sotos