Home > OS >  How to Divide a Grouping Variable into Two Variables with String Values in R?
How to Divide a Grouping Variable into Two Variables with String Values in R?

Time:10-15

I have a data that looks like this:

Exp1 <- structure(list(Duration = c(159L, 170L, 140L, 95L, 216L, 142L
), Group = c("Personal Failure", "Personal Failure", "Nonpersonal Failure", 
             "Nonpersonal Success", "Personal Success", "Nonpersonal Failure"
)), row.names = c(NA, 6L), class = "data.frame")

I want to divide the "Group" column into two different columns so that the first words of each value (Personal/Nonpersonal) makes up one column called "Type", the second word (Failure/Success) makes up another column called "Achivement".

How can I do it?

Here is an example output that I want to get:

Exp1 <- structure(list(Duration = c(159L, 170L, 140L, 95L, 216L, 142L
), type = c("Personal ", "Personal ", "Nonpersonal ", "Nonpersonal ", 
            "Personal ", "Nonpersonal "), achivement = c("Failure", "Failure", 
                                                         "Failure", "Success", "Success", "Failure")), row.names = c(NA, 
                                                                                                                     6L), class = "data.frame")

CodePudding user response:

library(tidyr)
library(dplyr)

Exp1 %>% 
  separate(col = Group,into = c("Type","Achievement"),remove = FALSE)

  Duration               Group        Type Achievement
1      159    Personal Failure    Personal     Failure
2      170    Personal Failure    Personal     Failure
3      140 Nonpersonal Failure Nonpersonal     Failure
4       95 Nonpersonal Success Nonpersonal     Success
5      216    Personal Success    Personal     Success
6      142 Nonpersonal Failure Nonpersonal     Failure

CodePudding user response:

Base R solution:

split_vec_name <- "Group"
cbind(
   Exp1[,names(Exp1) != split_vec_name, drop = FALSE],
   strcapture(
      pattern = "(\\w )\\s (\\w )",
      x = Exp1[,split_vec_name],
      proto = list(type = character(), achievement = character())
   )
)

CodePudding user response:

You may try

library(dplyr)

Exp1 %>%
  rowwise %>%
  mutate(Type = (strsplit(Group, " ") %>% unlist)[1],
         Achievement = (strsplit(Group, " ") %>% unlist)[2]) 

  Duration Group               Type        Achievement
     <int> <chr>               <chr>       <chr>      
1      159 Personal Failure    Personal    Failure    
2      170 Personal Failure    Personal    Failure    
3      140 Nonpersonal Failure Nonpersonal Failure    
4       95 Nonpersonal Success Nonpersonal Success    
5      216 Personal Success    Personal    Success    
6      142 Nonpersonal Failure Nonpersonal Failure
  • Related