-1

I have a dataframe that has numeric vector in a column and want to split the column into multiple columns. An example is given below for dataframe df with two columns a and b. Each column is composed of a vector of x and y values. I want to separate the numeric vectors into two columns x and y. The example only has two columns a and b but could have more.

What I found so far is that one can use tidyr:separate separate string based vector but not numeric vector. A similar question was also asked in this post for string based vector. R Split a column containing a vector into multiple columns. Another question was asked in this post which is directly related. https://community.rstudio.com/t/split-a-column-each-element-is-a-vector-to-multiple-columns/14009/6. I was wondering if there are better ways.

df <- tribble(
  ~a, ~b,
  c(1.2, 2.3), c(1.3, 2.4),
  c(3.4, 4.5), c(5.6, 7.8))

Expected dataframe would be a dataframe with four columns.

a.x   a.y   b.x   b.y
1.2   2.3   1.3   2.4
3.4   4.5   5.6   7.8
Jian
  • 365
  • 1
  • 6
  • 19

2 Answers2

0

This is a little ugly but should work:

df %>% 
  mutate_all(~ map_chr(., paste, collapse = ",")) %>% 
  separate(a, into = c("a.x", "a.y"), sep = ",") %>% 
  separate(b, into = c("b.x", "b.y"), sep = ",") %>% 
  mutate_all(as.numeric)
cardinal40
  • 1,245
  • 1
  • 9
  • 11
0

I am borrowing markus's answer here.

as.data.frame(lapply(df, function(x) t(do.call(cbind, x))))
Jian
  • 365
  • 1
  • 6
  • 19