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.
The basic installation of R provides a solution for the splitting of variables based on a delimiter. If we want to split our variable with Base R, we can use a combination of the data.frame, do.call, rbind, strsplit, and as.character functions.
If you want to split one data frame column into multiple in R, then here is how to do that in 3 different ways. Here is the data frame that I created from the mtcars dataset. I will split this column using space as a delimiter, and to do that, I will create two calculations. The first calculation is the count of space characters in a string.
One of the best solutions to split column by delimiter is function separate from the tidyr. In the description of function separate are a couple of examples. There is a lot of parameters that can be useful to do some configurations for the desired result. By the default function separate will remove the original column.
The strsplit () function is extensively used and most popular in terms of splitting the strings. In the R language, we use the paste () function to concatenate and the strsplit () function to split the string. Let’s see how to split the string.
You can use mutate
and gsub
:
library(dplyr)
df = df %>% mutate(D=gsub("\\..*","",A))
A B C D
awer.ttp.net Code 554 awer
abcd.ttp.net Code 747 abcd
asdf.ttp.net Part 554 asdf
xyz.ttp.net Part 747 xyz
We can use tidyverse
for this
library(dplyr)
library(tidyr)
df1 %>%
separate(A, into = 'D', extra = 'drop', remove = FALSE) %>%
select(LETTERS[1:4])
# A B C D
#1 awer.ttp.net Code 554 awer
#2 abcd.ttp.net Code 747 abcd
#3 asdf.ttp.net Part 554 asdf
#4 xyz.ttp.net Part 747 xyz
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With