Home > database >  Replace stars (***) with numbers
Replace stars (***) with numbers

Time:04-30

I have a data frame that I exported from lightroom to R. In this data frame there is a grading system for the photographs where each is graded with stars from 1 (*) to 5 (*****) I want to replace these stars with numbers but tried several functions (gsub, replace) with no success

Lightroom$Rating <- gsub("*", "1", Lightroom$Rating)

Lightroom <- replace(Lightroom, "*", "1")

Thank you for your help

CodePudding user response:

If I understand your question correctly, you want to replace the number of stars with the actual count. This allows some flexibility in case you want to do something else with each matched number of asterisks (*).

library(tidyverse)

Lightroom <- data.frame(Rating = c("*",
                                   "**",
                                   "***",
                                   "****",
                                   "*****"))
Lightroom_subbed <- Lightroom %>% 
  mutate(Rating2 = case_when(grepl(x = Rating, pattern = "^\\*{1}$") ~ "1",
                             grepl(x = Rating, pattern = "^\\*{2}$") ~ "2",
                             grepl(x = Rating, pattern = "^\\*{3}$") ~ "3",
                             grepl(x = Rating, pattern = "^\\*{4}$") ~ "4",
                             grepl(x = Rating, pattern = "^\\*{5}$") ~ "5"
  )
  )
Lightroom_subbed
 Rating Rating2
1      *       1
2     **       2
3    ***       3
4   ****       4
5  *****       5

CodePudding user response:

Much simpler approach is available. Use the factor data-type's underlying integer structure:

as.numeric(factor(Lightroom$Rating))
[1] 1 2 3 4 5
  •  Tags:  
  • r
  • Related