Function to add column which is named based on variable

I'm trying to add a column to a dataframe within a function.

My underlying question is: how does one pass a variable name into a function in a way that this variable can be used to address specific columns?

I've read quite a few posts with similar questions, and I can add the column with some code I copy/pasted, but I really need/want understanding why/how of how it works.

Here's the basic working example:

abby <- tibble(a = 1:20)

bill <- function(x, nc) {
  x  = x %>% add_column(!!nc := 0)
}

newabby <- bill(abby, "newCol")

This does what I need. It adds a column based on the variable given to the function.

newabby looks like this

# A tibble: 20 x 2
       a newCol
   <int>  <dbl>
 1     1      0
 2     2      0
 3     3      0
...

Here are my questions:

  • What does the "!!" mean and do in this function? (I've tried google and read like 4 posts on R operators and still have no idea

  • Same question for the ":"?

  • Why does this not work:

bill <- function(x, nc) {
  x[,nc} <-0 
}

where something like

bill <- function(x, nc) {
print(x[,nc])
}

works fine?

Let me ask about another example:
(Since I already have your attention and you're being very kind by reading this.)

I need to iterate through rows, addressing a column the name of which comes from a variable given to the function.

I want to use a loop to perform a function row by row. In other words, I want to do what is shown below, but need to be able to choose the column by passing a variable to the function.

I start with abby

abby <- tibble(a = 1:30)

and here's what I want to do

for (i in 1:20) {
  print(abby$a[i])
}?

I can do this but the result is similar, but not quite the same:

eddie <- function(x, clmn) {
 for (i in 1:20) {
   print(x[i, clmn])
   }
}

How would I do this same thing as the eddie function above, but for the x$clmn[i] format, not the x[i, clmn] format?

Thanks so much for any help!

Please be more explicit about what works (as you expect) and what not.
E.g. for what arguments of functions does it work or not.
In one of the cases you had a typo

bill <- function(x, nc) {
  x[,nc} <-0 
}

what explains a lot.

See the help information for package rlang for !! and := definitions: ?rlang::`nse-force`

Thank you! This is extremely thankful.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.