0

Just a quick question around how I can split a variable.

I have a created a data frame called d.

R code is shown below.

x1 = c(1, 2, 3, 4)
x2 = c(5, 6, 7, 8)
x1x2 = paste(x1, x2, sep = ",")

x3 = c(10, 20)
x4 = c(100, 200, 300, 400, 500)

d = data.frame(expand.grid(x1x2, x3, x4))

From data d, how can I split x1x2 variable so that x1 and x2 are separated?

Many thanks in advance.

Brian
  • 161
  • 11

2 Answers2

1

If you mean create separate columns for x1 and x2, you can use tidyr::separate:

library(tidyverse)
d2 <- d %>% 
  separate(Var1, sep = ",", into = c("x1", "x2"))

head(d2)

  x1 x2 Var2 Var3
1  1  5   10  100
2  2  6   10  100
3  3  7   10  100
4  4  8   10  100
5  1  5   20  100
6  2  6   20  100
neilfws
  • 32,751
  • 5
  • 50
  • 63
0

You could use regular expressions

d$x1 <- gsub(".*?,","",d[[1]])
d$x2 <- gsub(",.*","",d[[1]])

or

?strsplit
Brian Davis
  • 990
  • 5
  • 11