How assign the value

If I have a dataframe named "addition_colors" and variable called "colors" with values .


See below


#one way of doing it
c <- 0

addition_colors <- c(c + 2,c + 4, c+7) %>%

names(addition_colors) <- "colors"

#mutate way of doing it
df <- data.frame(colors = c(2,4,7),
                 c = c(0,0,0))

df <- df %>% mutate(colors_calc = colors + c)

Created on 2020-10-16 by the reprex package (v0.3.0)

colors has hundred of values etc

I was wondering if there was a more efficient way without having to go through each one

Look at the second option with mutate. You specify the formula once.

Maybe I'm misundertanding your issue but just to be sure, Do you mean that inside your colors variable you have text values like "c+1" and you want to convert them to 1?

If that is the case then you can do it like this


# Sample data on a copy/paste friendly format, replace whit your own data
addition_colors <- data.frame(
    stringsAsFactors = FALSE,
    colors = c("c+2", "c+4", "c+7")

addition_colors %>% 
    mutate(colors_calc = as.numeric(str_extract(colors, "\\d+$")))
#>   colors colors_calc
#> 1    c+2           2
#> 2    c+4           4
#> 3    c+7           7

Created on 2020-10-16 by the reprex package (v0.3.0)

If this doesn't solve your problem, please provide a proper REPRoducible EXample (reprex) illustrating your issue.