In a column, how can I recode data that is in a sequence?

Viewed 51

In my data-frame, I have a column named "Colors". The data in the Colors column looks like this:

Red001.jpeg
Red002.jpeg
Red003.jpeg
Red004.jpeg
... you get the pattern...
Red999.jpeg

Blue001.jpeg
...
Blue999.jpeg

Green001.jpeg
...
Green999.jpeg

Yellow001.jpeg
...
Yellow999.jpeg

I want to change Red001.jpeg through Red999.jpeg into Red. Likewise, I need to do this with Blue, Green and Yellow as well. How can I automate this process?

3 Answers

A simple regex will do it.

sub("(^[[:alpha:]]+)[[:digit:]]*.*", "\\1", color)
# [1] "Red"    "Red"    "Red"    "Red"    "Red"    "Blue"  
# [7] "Blue"   "Green"  "Green"  "Yellow" "Yellow"

Data.

color <- scan(what = character(), text = "
Red001(dot)jpeg
Red002(dot)jpeg
Red003(dot)jpeg
Red004(dot)jpeg
Red999(dot)jpeg
Blue001(dot)jpeg
Blue999(dot)jpeg
Green001(dot)jpeg
Green999(dot)jpeg
Yellow001(dot)jpeg
Yellow999(dot)jpeg
")

We can use the regular expression.

dat$V1 <- sub("[0-9]{3}\\.jpeg$", "", dat$V1)

Data

dat <- read.table(text = "Red001.jpeg
Red002.jpeg
                  Red003.jpeg
                  Red004.jpeg
                  Red999.jpeg
                  Blue001.jpeg
                  Blue999.jpeg
                  Green001.jpeg
                  Green999.jpeg
                  Yellow001.jpeg
                  Yellow999.jpeg",
                  header = FALSE, stringsAsFactors = FALSE)

Looks like pattern is [colour][3 digits][dot][jpeg]. Then we can use substring without regex:

substring(dat$V1, first = 1, last = nchar(dat$V1) - 8)

# [1] "Red"    "Red"    "Red"    "Red"    "Red"    "Blue"   "Blue"   "Green" 
# [9] "Green"  "Yellow" "Yellow"

Or fun solution, looks like each colour is repeated 999 times:

rep(c("Red", "Green", "Blue", "Yellow"), rep(999, 4))
Related