'Replace stars (***) with numbers

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

r


Solution 1:[1]

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

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 IRTFM