Home > front end >  Split a string by commas into multiple columns in R
Split a string by commas into multiple columns in R

Time:12-28

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?

CodePudding user response:

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

CodePudding user response:

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))
  • Related