Question

Here's my data frame.

    > data
       Manufacturers  
1   Audi,RS5  
2   BMW,M3  
3   Cadillac,CTS-V  
4   Lexus,ISF

So I would want to split the manufacturers and the models, like this,

    > data
    Manufacturers       Models
1   Audi                RS5  
2   BMW                 M3  
3   Cadillac            CTS-V  
4   Lexus               ISF

I would appreciate any help on this question. Thanks a lot.

Was it helpful?

Solution

Some sample data. You could use a character vector, but I'll use a data frame to match your example:

df <- data.frame(Manufacturers = c("Ducati,Diavel", "Honda,Goldwing",
                                   "BMW,R1200GS", "Harley-Davidson,Fat Boy"),
                 stringsAsFactors = FALSE)

Use strsplit() to separate the strings. Note that it requires a character (not a factor) vector. Strsplit() returns a list object:

list <- strsplit(df$Manufacturers, ",")

Transform the list into a data frame and set appropriate column names:

library("plyr")
df <- ldply(list)
colnames(df) <- c("Manufacturer", "Model")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top