-1

So I have a dataset (states) - the built-in R dataset, in fact.

States have 9 variables.

> names(states)
[1] "Population" "Income"     "Illiteracy" "Life.Exp"   "Murder"     
"HS.Grad"    "Frost"      "Area"      
[9] "Region" 

I am interested in seeing the unique levels within each variable.

For one variable, I can do

> unique(states$Region)
[1] South         West          Northeast     North Central
Levels: Northeast South North Central West

How can I repeat this process for all 9 variables?

> unique <- function(var){
+   unique(states$var)
+ }
> lapply(names(states),unique)

Error: evaluation nested too deeply: infinite recursion / 
options(expressions=)?
Error during wrapup: evaluation nested too deeply: infinite recursion / 
options(expressions=)?

Why does this error appear? And how can I fix this?

Thanks!

Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
R Newbie
  • 57
  • 6
  • 2
    `lapply(states, unique)` ? – Ronak Shah Dec 15 '17 at 05:51
  • 3
    You overwrite `unique`, which you should **never** do, especially not, if you want to use that function (that's why error says "infinite recursion"). Otherwise you would have to use `base::unique`, such that your code changes to `unique <- function(var) base::unique(states[[var]])` but please don't do that. Just use what @RonakShah suggests. – Tino Dec 15 '17 at 06:59

2 Answers2

0

You can use apply

apply(states,2,unique)
axiom
  • 406
  • 1
  • 4
  • 16
0

Note the difference in the value returned by apply and lapply, it can be an issue. Working with lapply (as suggested by Ronak Shah) will gives you a list and keep the class of your variables. The result of apply (as suggested by axiom) can result in a list of character if one of your variable is a character. Here is an example with the diamonds data (the first 10 rows only). If you prefer to obtain a list with similar class objects, I recommend apply; otherwise, lapply is more convenient.

df = diamonds[1:10 , ]
apply(df, 2, unique)
lapply(df, unique) 
Rtist
  • 3,825
  • 2
  • 31
  • 40
  • I did not notice your comments.Sorry about that. I gave you the credit in my answer and just added the comparison between the value of apply and lapply. – Rtist Dec 15 '17 at 07:28