1

I'm trying to understand this peice of code in R:

thing <- low_temp %>% filter(room_type == "bedroom" & score == "6") %>% .[, "n"] %>% sum()

the meaning of the code .[, "n"] is not clear, and since it is completely written in shorthand, it is impossible to search for it in Google.

Obviously [, x] is just base R. But the use of the dot bracket notation is not something I've seen anywhere in my admittedly limited foray into R through udemy and hadley & wickem's book. And I'm guessing that the use of "n" is also not consistent with recent R coding standards. The data frame in question comtains a column n.

My take on it is that R has been around for a long time, and like most open languages has undergone a lot of expansion without strict enough editing, which results in a huge amount of grammatical redundancy. That being the case, I feel very strongly that notation like the one here that stumped me should be systematically phased out of usage as they are unclear; impossible to search and difficult to read.

All that said, my question is quite simply, what does the dot bracket mean in the %>% .[, "N"]. And secondly, what is the reason for the use of double commas around n?

monkey
  • 1,213
  • 2
  • 13
  • 35

2 Answers2

2

Here is an example with mtcars, is basically selecting a column by the name, but it returns a vector, diferent from select(), that returns a data.frame

    mtcars %>% 
       select("cyl") %>% 
       pull()

     [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4

    mtcars %>% 
       .[,"cyl"]

     [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4

    mtcars$cyl

     [1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4
Vinícius Félix
  • 8,448
  • 6
  • 16
  • 32
  • got it. Since I'm always following with sum(), I can use select instead with no change in behaviour, but increased readability of my code. – monkey Aug 31 '21 at 02:39
1

Let df = low_temp %>% filter(room_type == "bedroom" & score == "6") then .[, "n"] means df[, "n"] (== df$n)

Park
  • 14,771
  • 6
  • 10
  • 29