0

Having a dataframe like this:

dframe <- data.frame(id = c(1,2), names = c("google analytics","amazon shop"))

Which command could create two columns using the space of names column?

Example output:

dframe <- data.frame(id = c(1,2), names1 = c("google","amazon"), names2 = c("analytics","shop"))
harre
  • 7,081
  • 2
  • 16
  • 28
Erik Brole
  • 315
  • 9

2 Answers2

-1

Another solution is with extract:

library(tidyr)
dframe %>%
  extract(names,
          into = c("names1", "names2"),
          regex = "(\\w+) (\\w+)")
  id names1    names2
1  1 google analytics
2  2 amazon      shop
Chris Ruehlemann
  • 20,321
  • 4
  • 12
  • 34
-2

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
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341