rdynamictidyversemutate

Count number of characters with column name in dynamic variable


Provided that here there is written that I can pass {{colname}} to mutate, where colname is a variable that contains a column name, I cannot figure out why this code doesn't work:

testdf <- data.frame(a=c("Hello", "Hi", "Howy"))
varname <- "a"
testdf %>% mutate(b=nchar({{varname}}))

It returns the number of characters in the letter a:

      a b
1 Hello 1
2    Hi 1
3  Howy 1

How can I count the number of characters in a column and assign the value to another column, when the name of the first column is saved into a variable?


Solution

  • The issue arises because {{varname}} doesn't evaluate to the content of the variable varname when you use it inside mutate().

    In this case, {{varname}} is treated literally, which is why you're only seeing 1 for each row.

    To solve this, you can simply use base R for a straightforward solution. Here’s how you can do it:

    # Create a data frame
    testdf <- data.frame(a = c("Hello", "Hi", "Howy"))
    
    # Variable storing column name
    varname <- "a"
    
    # Use base R to add a column `b` with character counts
    testdf$b <- nchar(testdf[[varname]])
    

    OUTPUT

          a  b
    1 Hello  5
    2    Hi  2
    3  Howy  4