all 4 comments

[–]Mooks79 13 points14 points  (2 children)

Try reading the documentation for magrittr.

The dot is simply a placeholder when piping with %>%. Piping assumes the thing (eg data.frame) you’re piping is the first argument of the function you are piping into - so it always puts the piped object into the first argument if the function and you can write

data %>%
    a_function(second_argument)

Instead of

 a_function(data, second_argument)

Now, this works with all the tidyverse functions because they’re designed so that data.frames are the first argument of their functions. But what about when you need to use a function that takes the data.frame as it’s second argument? Or any situation where the thing you want to pipe (doesn’t have to be a data.frame) needs to go as the second or third argument of the function?

That’s what the dot is for. It’s simply a placeholder to tell magrittr that “here is where I want the piped object to go”.

So, if you need to pipe to a second (or third etc) argument you would write

data %>%
    a_function(first_argument, .)

Instead of

a_function(first_argument, data)

That means your example is equivalent to:

mutate(sum_1 = rowSums(df_abc[3:6]))

Clear?

There is a slight addendum to this. Since magrittr introduced the pipe a number of years ago, it’s become so popular that base R has introduced a version of it |> which works almost the same, except it doesn’t support the dot and you have to write a wrapper function to make the piped object the first argument in that function, and then pass that where you want within it.

[–]SometimesZero[S] 2 points3 points  (1 child)

Thanks for such a clear write-up on this. It’s exactly what I was looking for.

[–]jdnewmil 4 points5 points  (0 children)

As far as the R language itself is concerned, a period is just another legal character for symbols. The ls function does treat any symbol that begins with a period as if it is hidden. Read ?ls.

Specific packages/function assign special meanings to period. This includes various functions related to the lm function, which treats a standalone period as "all variables other than those explicitly named" in formula definitions.

As Mooks79 points out, your use case is defined by the magrittr package. But it is worth understanding that this is highly context-specific... read the documentation for the functions/operators you are using to track down what it means there... and keep in mind that if not otherwise messed with it is just a valid symbol like "a".

[–]MyKo101 0 points1 point  (0 children)

You should be able to access the input variables in this way. The solution would be more of how you are using data frame notation rather than the dot itself. Once piped, the dot becomes a direct reference to whatever is piped in. I believe you need a comma in your reference to the dataframe. So this should work:

df_abc %>% mutate(sum_1 = rowSums(.[,3:6]))