Split 1 Column into 2 Columns in a Dataframe [duplicate]

半腔热情 提交于 2019-12-02 23:52:07

问题


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.


回答1:


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")


来源:https://stackoverflow.com/questions/16248861/split-1-column-into-2-columns-in-a-dataframe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!