Ask Your Question
4

How can a data.frame with only one column be divided into several columns in R?

asked 2023-07-01 15:23:29 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2023-07-01 15:42:02 +0000

nofretete gravatar image

One way to divide a data frame with only one column into several columns in R is to use functions like separate() or tidyr::extract().

For example, let's say we have a data frame df that contains only one column "Name" with values like "John Doe", "Sara Smith", and "Mike Johnson". We want to split this into two columns "FirstName" and "LastName".

We can use tidyr::separate() function as follows:

library(tidyr)

df_new <- separate(df, Name, into = c("First_Name", "Last_Name"), sep = " ")

This will create a new data frame df_new with two columns "FirstName" and "LastName" containing the separated values.

Alternatively, we can use tidyr::extract() function as follows:

df_new <- extract(df, Name, into = c("First_Name", "Last_Name"), regex = "^(\\S+)\\s+(\\S+)$")

This will create a new data frame df_new with two columns "FirstName" and "LastName" containing the extracted values using a regular expression.

Note that in both cases, we need to specify the column to be separated or extracted, and the names of the new columns to be created.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-07-01 15:23:29 +0000

Seen: 14 times

Last updated: Jul 01 '23