0

I have some idea as to how to select columns using .[] and .$ in dplyr.

Here is a reprex:-

library(dplyr)
> mtcars%>% .["disp"] %>% head
                  disp
Mazda RX4          160
Mazda RX4 Wag      160
Datsun 710         108
Hornet 4 Drive     258
Hornet Sportabout  360
Valiant            225
> mtcars%>% .$"disp" %>% head
[1] 160 160 108 258 360 225
> 

I wish to read the help page the .[] and .$ How can I do this ? My googling was not successful so I came here. Can someone point me in the right direction ?

I am using this inside mutate.

> library(dplyr)
> names(mtcars)
 [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear"
[11] "carb"
> chosen_cols <- c("disp","drat")
> library(dplyr)
> mtcars %>% mutate(answer = rowSums(.[chosen_cols]))

Here is how we can select rows :-

mtcars %>% head %>% .[1,]

          mpg cyl disp  hp drat   wt  qsec vs am gear carb
Mazda RX4  21   6  160 110  3.9 2.62 16.46  0  1    4    4
> 
user2338823
  • 501
  • 1
  • 3
  • 16
  • 1
    Why do you want to use .[] or .$ rather than dplyr::mutate ? Could you give us insights? – linog Apr 09 '20 at 06:26
  • 2
    You don't need `[` or `$` in `dplyr` most of the time . As far as answer to your question is concerned you can refer https://stackoverflow.com/questions/1169456/the-difference-between-bracket-and-double-bracket-for-accessing-the-el – Ronak Shah Apr 09 '20 at 06:30
  • `mtcars%>% .[["disp"]] %>% head`. VTC as duplicate. – Rui Barradas Apr 09 '20 at 06:36
  • I do have some idea of how to USE .[] and .$ ,I am not able to access the help page for them. That page pointed to by @RonakShah does NOT say how .[] can be used to select columns which is what I am doing. Can someone show me how to read the help page for .[] in the context of selecting columns – user2338823 Apr 09 '20 at 06:42
  • linog, please see my edit in response to your query. – user2338823 Apr 09 '20 at 06:46
  • Help page for all are present in `?Extract` and this works as expected right? `mtcars %>% mutate(answer = rowSums(.[chosen_cols]))` – Ronak Shah Apr 09 '20 at 06:47
  • It does seem to work as expected,I have another related query .[chosen_cols] selects *columns*, how can I select *rows* using . notation – user2338823 Apr 09 '20 at 07:28
  • Answered this query by editing the original query, please see above. – user2338823 Apr 09 '20 at 08:40

0 Answers0