0

To create a new column in data :

library("titanic")
traint <- titanic_train

I use :

traint["newCol"] <- traint['Survived'] == 1

or

traint$newCol <- traint['Survived'] == 1

The newly created column added to traint data appear equivalent.

Which method should I choose when creating a new column within data ? ["newColName"] or $newColName ? Are both methods of creating the new column equivalent ?

lmo
  • 37,904
  • 9
  • 56
  • 69
blue-sky
  • 51,962
  • 152
  • 427
  • 752
  • 1
    You can also use `[[<-`: `traint[["newCol"]] <- traint[['Survived']] == 1`. I'd recommend you read (and reread) `?Extract` and `?"[.data.frame"`. These are the answers you seek. – lmo Oct 07 '17 at 11:55
  • 1
    [This post](https://stackoverflow.com/questions/18222286/dynamically-select-data-frame-columns-using-and-a-vector-of-column-names) and [this post](https://stackoverflow.com/questions/4605206/drop-data-frame-columns-by-name) may also provide some perspectives. – lmo Oct 07 '17 at 12:06
  • 1
    I removed the rstudio tag as this should only be used for questions that involve the IDE. This question is about standard R. – lmo Oct 07 '17 at 12:29
  • The way you use `[ ` and `$` in your example, there is no difference (or at least none that matters). If, however, the name of the column to be created is stored in a variable, you can not use `$`. – Stibu Oct 07 '17 at 14:14

0 Answers0