Here are some alternatives using the first instance of dframe
given in the question.
1) separate Use separate
as shown below:
library(dplyr)
library(tidyr)
dframe %>% separate(names, into = c("names1", "names2"))
## id names1 names2
## 1 1 google analytics
## 2 2 amazon shop
2) sub or using base R only with sub
transform(dframe, names1 = sub(" .*", "", names),
names2 = sub(".* ", "", names),
names = NULL)
## id names1 names2
## 1 1 google analytics
## 2 2 amazon shop
3) read.table or using base R only with read.table
cbind(dframe[-2],
read.table(text = dframe[[2]], col.names = c("names1", "names2")))
## id names1 names2
## 1 1 google analytics
## 2 2 amazon shop
3a) Another way to use read.table is
tmp <- read.table(text = dframe$names)
transform(dframe, names1 = tmp[[1]], names2 = tmp[[2]], names = NULL)
3b) Yet another read.table approach is to paste together the fields in each row and then use read.table on that.
nms <- c("id", "names1", "names2")
read.table(text = with(dframe, paste(id, names)), col.names = nms)
## id names1 names2
## 1 1 google analytics
## 2 2 amazon shop
4) sapply/strplit Another base R solution can be obtained using sapply
and strsplit
. We define a field
function for convenience.
field <- function(x, i) sapply(strsplit(x, " "), `[`, i)
transform(dframe, names1 = field(names, 1),
names2 = field(names, 2),
names = NULL)
## id names1 names2
## 1 1 google analytics
## 2 2 amazon shop