Divide columns in R by number in data frame

I am trying to separate a column in a rather messy frame.

section
View 500
V458
453

And I want to create a new column from this. With preferred output as shown below.

section  section numbers  
View     500
V        458
         453

I tried to explore it, but I have time with it. I can separate them in the case of the first line, because I can use a regular expression like this.

df_split <- separate(df, col = section, into = c("section", "section_number"), sep = " +[1-9]")

But I can’t find a way to use a type operator or. If anyone has any input that would be great.

+4
source share
5 answers

Using simple gsubwould be my choice:

section <- c('View 500', 'V458', '453')

cbind(section = trimws(gsub('[0-9]', '', section)), 
      section_numbers = trimws(gsub('[a-zA-Z]', '', section)))

I use trimwsto simply remove the extra spaces.

Conclusion:

    section section_numbers
[1,] "View"  "500"          
[2,] "V"     "458"          
[3,] ""      "453" 
+6

tidyr :

tidyr::extract(df,section, c("section", "section number"), 
               regex="([[:alpha:]]*)[[:space:]]*([[:digit:]]*)")
  section section number
1    View            500
2       V            458
3                    453
+5

extract, tidyr, , , :

library(tidyr)
df %>% extract(section, into = c("alpha", "numeric"), regex = "([a-zA-Z]+)?\\s?(\\d+)?")

#  alpha numeric
#1  View     500
#2     V     458
#3  <NA>     453
+3

base R read.csv sub. ((\\d+)$) (\\1) sub read.csv

read.csv(text=sub("\\s*(\\d+)$", ",\\1", df1$section), fill=TRUE, header=FALSE, 
         col.names = c("section", "section number"), stringsAsFactors=FALSE)
#   section section.number
#1    View            500
#2       V            458
#3                    453
+1

stringr ( df section):

library(stringr)
df_split <- as.data.frame(str_match(df$section, "([A-Za-z]*)\\s*([0-9]*)")[,2:3])
names(df_split) <- c('section', 'section numbers')
df_split

#  section section numbers
#1    View             500
#2       V             458
#3                     453
0

Source: https://habr.com/ru/post/1664717/


All Articles