-3

I need to split a column into two columns. My data is in csv file, and I imported that into R. This is the code I am using installed tidyr package

data$CarName <- separate(data$CarName, c("Car Name", "Car Model"), sep = " ")

error

Error in UseMethod("separate_") : no applicable method for 'separate_' applied to an object of class "factor"

Any help?

2
  • 2
    separate works on a dataframe and not on a column. It may be separate(data, carName ,into = c("CarName", "CarModel"), sep= " ") It is better to show a small reproducible example
    – akrun
    Jul 27, 2018 at 7:28
  • Put your data head in your question
    – Saman
    Jul 27, 2018 at 7:30

1 Answer 1

1

Assuming the data from the .csv file was separated with spaces, you might want to look into str_split_fixed from the stringr package. Based on the info you provided, the code would look something like this:

 carname <- "Carname CarModel"
 data <- data.frame(carname)
 data$name <- str_split_fixed(data$carname,n = 2,pattern = " ")[1]
 data$model <- str_split_fixed(data$carname,n = 2,pattern = " ")[2]

Resulting in:

 data
           carname    name    model
 1 Carname CarModel Carname CarModel

If your data was, e.g. comma-seperated, just replace the pattern in the str_split_fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.