Home > Mobile >  How to separate rows of a column into multiple other columns in R?
How to separate rows of a column into multiple other columns in R?

Time:03-07

Consider this data: "0 - 1" "1 - 1" "1 - 1" "1 - 0" "0 - 0" "1 - 0" "1 - 1" "1 - 1" "1 - 0" "0 - 1" which is a column called X in a data frame. I would like to form 4 columns out of X: A,B,C,D. A is 1-1, B is 0-1, C is 1-0, and D 0-0.

How can I do this in R please ? Thank you in advance.

CodePudding user response:

Something like this? Not totally sure what your expected output is. But you could create a key for what components you want to go in each column. Then, we could join to the key then use that to put the data into a wide format.

library(tidyverse)

key <- data.frame(tag = c("A", "B", "C", "D"),
           X = c("1 - 1", "0 - 1", "1 - 0", "0 - 0"))

df %>%
  left_join(., key, by = "X") %>%
  group_by(tag) %>%
  mutate(id = row_number()) %>%
  arrange(tag) %>%
  pivot_wider(names_from = tag, values_from = X) %>%
  select(-id)

Output

  A     B     C     D    
  <chr> <chr> <chr> <chr>
1 1 - 1 0 - 1 1 - 0 0 - 0
2 1 - 1 0 - 1 1 - 0 NA   
3 1 - 1 NA    1 - 0 NA   
4 1 - 1 NA    NA    NA   

Data

df <- structure(list(X = c("0 - 1", "1 - 1", "1 - 1", "1 - 0", "0 - 0", 
"1 - 0", "1 - 1", "1 - 1", "1 - 0", "0 - 1")), class = "data.frame", row.names = c(NA, 
-10L))
  •  Tags:  
  • r
  • Related