0

Say I have a data table like this in R:

Data Table

And I want to a add column to this table which indicates if the person switched majors (like "Y" for switched, "N" for didn't switch), how would I do that? I've tried using the count and unique functions but don't know how to proceed.

Harshi
  • 1
  • 1
  • 2
  • How do you know if major is switched? If the `ID` has only one entry then it is not switched? – Ronak Shah Dec 22 '17 at 04:16
  • If the ID repeats further down the table, then the major was switched – Harshi Dec 22 '17 at 04:31
  • One way to solve this is by using `ave` and `ifelse`: `ifelse(ave(df$Major, df$ID, FUN = length) > 1, "Y", "N")`. Also instead of posting images try to give `dput()` of your dataframe which might be helpful for others to help you. See [here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Ronak Shah Dec 22 '17 at 04:41
  • Use `ave` and `max(seq_along(ID))>1`. – IRTFM Dec 22 '17 at 04:48
  • Thanks Ronak, but your solution gave me a vector of just "Y"s. 42, thank you but your idea returned an integer. – Harshi Dec 22 '17 at 04:51

1 Answers1

1

You can simply add a column IsSwitched by using by clause of data.table:

DT[, IsSwitched:= ifelse(.N>1,"Y","N"), by=Id]

Where DT is your data.table.

MKR
  • 19,739
  • 4
  • 23
  • 33