robertspierre
robertspierre

Reputation: 4431

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?

Upvotes: 0

Views: 62

Answers (3)

Friede
Friede

Reputation: 7979

As it is designed like

library(dplyr)
f = \(dd, var) mutate(dd, b = nchar( {{var}} ))

giving

> f(testdf, a) # no quotes
      a b
1 Hello 5
2    Hi 2
3  Howy 4

As user @AndreWildberg points out in a comment, you will need to swap to

f2 = \(dd, var) mutate(dd, b = nchar( !!sym(var) ))

giving

> f2(testdf, "a") # quotes
      a b
1 Hello 5
2    Hi 2
3  Howy 4

Upvotes: 1

Nirav
Nirav

Reputation: 81

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
  • testdf[[varname]] retrieves the column specified by varname from testdf.
  • nchar(testdf[[varname]]) counts the characters in each element of that column.
  • testdf$b <- ... assigns these counts to a new column b in testdf.

Upvotes: 1

stefan
stefan

Reputation: 125398

As varname is a character you can use the .data pro-noun:

testdf <- data.frame(a = c("Hello", "Hi", "Howy"))
varname <- "a"

library(dplyr, warn = FALSE)

testdf %>%
  mutate(b = nchar(.data[[varname]]))
#>       a b
#> 1 Hello 5
#> 2    Hi 2
#> 3  Howy 4

Upvotes: 1

Related Questions