-2

I'm new to R. I have a single column (yes, just one column) with 200 rows whose elements are strings separated by commas.

Actual data:

"A, B, C, D"
"1, 10, 13, 4"
"0, 1, 6, 1"
"9, 3, 3, 0"
...

And from this single column I want to produce de following data frame:

A   B   C   D

1   10  13  4
0   1   6   1
9   3   3   0
     ...

Where "A", "B", "C", "D" are the column-headers for this data frame and the rows also split by comma to each of the created column respectively. How can I achieve this in R?

bgly
  • 157
  • 8
  • 1
    Where do you "have" your single column, please be more specific! Carefully read [how-to-make-a-great-r-reproducible-example](https://stackoverflow.com/a/5963610/6574038). – jay.sf Dec 27 '21 at 23:09

2 Answers2

3

Try read.table like below

> read.table(text = df$Col1, header = TRUE, sep = ",")
  A  B  C D
1 1 10 13 4
2 0  1  6 1
3 9  3  3 0
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
  • I'm sorry but "Col1" doesn't exist, it was a typo. Is there any way I can just say I want that Column with those headers? – bgly Dec 27 '21 at 22:46
0

Here is an alternative approach:

library(tidyverse)
library(janitor)

str_split_fixed(df$V1, ", ", 4) %>% 
  row_to_names(.,1) %>% 
  as_tibble()
  A     B     C     D    
  <chr> <chr> <chr> <chr>
1 1     10    13    4    
2 0     1     6     1    
3 9     3     3     0 

data:

structure(list(V1 = c("A, B, C, D", "1, 10, 13, 4", "0, 1, 6, 1", 
"9, 3, 3, 0")), class = "data.frame", row.names = c(NA, -4L))
TarJae
  • 72,363
  • 6
  • 19
  • 66