3

I am quite new to R and I am mainly learning by visiting these Q&A sites. I initially wanted to post a comment on a previous question, that partially answerd my question, but was unable to beacause of my reputation, as I just became a member.

Link to question: https://stackoverflow.com/a/16160671/4681908

What I want to do is to create a new column that counts the unique values for a varialbe in my dataset for unique IDs. Instead of getting a list as the following code:

with(mydf, tapply(Spp, Cnty, FUN = function(x) length(unique(x))))

,I would like to code it to a new variable. Could anyone help me with this? I am sorry for any lack of information, and thank you in advance

Community
  • 1
  • 1
Ole
  • 33
  • 1
  • 3
  • Use `ave` and convert `Spp` to a `character` as in `with(mydf, ave(as.character(Spp), Cnty, FUN = function(x) length(unique(x))))` – David Arenburg Mar 17 '15 at 17:32
  • @DavidArenburg But, this will return a character output. As the `Spp` is already a factor, it is better to convert to `numeric` to return numeric values – akrun Mar 17 '15 at 17:33
  • @arkrun, yeah `as.numeric` could be used too. I just wanted to illustrate one possibility. Though it seems you also added this. I'm sure this is a some type of a dupe that should be closed anyway. – David Arenburg Mar 17 '15 at 17:36
  • @DavidArenburg It could be a dupe, I haven't searched for any. If you find it, close it. – akrun Mar 17 '15 at 17:37

1 Answers1

5

Try n_distinct from dplyr

library(dplyr)
mydf %>% group_by(Cnty) %>% mutate(Count=n_distinct(Spp))

Or uniqueN from data.table

library(data.table)
 setDT(mydf)[,Count:=uniqueN(Spp) ,by = Cnty][]

Or use ave instead of tapply. As 'Spp' is a 'factor' column, you can use 'as.numeric'

mydf$Count <-  with(mydf, ave(as.numeric(Spp), Cnty,
                      FUN=function(x) length(unique(x))))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • 2
    mydf$Count <- with(mydf, ave(as.numeric(Spp), Cnty, FUN=function(x) length(unique(x)))) Worked perfectly. Thank you so much – Ole Mar 17 '15 at 19:59