R Split String By Delimiter in a column

Viewed 16074

I have a file with several lines. For example

A               B       C    
awer.ttp.net    Code    554
abcd.ttp.net    Code    747
asdf.ttp.net    Part    554
xyz.ttp.net     Part    747

I want to use R to split just column A of the table and I want a new column added to the table D, with values awe, abcd, asdf, and xyz. Would prefer this to be done using dplyr.

3 Answers

First I create the dataframe:

library(dplyr)

data <- 
   data.frame(
        A=c("awer.ttp.net","abcd.ttp.net", "asdf.ttp.net", "xyz.ttp.net"),
        B=c("Code", "Code", "Part", "Part"),
        C=c(554,747,554,747), 
        stringsAsFactors = F
   )

Then mutate the new column this way:

data %>% 
    mutate(
        D = strsplit(A, "[.]") %>% 
            as.data.frame() %>% 
            t %>% 
            data.frame(stringsAsFactors = F) %>% 
            pull(1)
   )
Related