0

I am new to R and am struggling to create assign a set of bins to a data frame that contains a set of numbers. Such as:

value
21
53
1
43
56

If I run hist then I know I can assign these values to a bin but that gives me a graphical output. How do I assign the bins to a new column in a data frame, i.e.,

value  class
21     20
53     50
1      0
43     40
56     50
jonsca
  • 10,218
  • 26
  • 54
  • 62

2 Answers2

0

RTM, i.e. the help page. hist has an argument that suppresses plotting. In any case it returns a list with values for the breaks and the counts.

str(hist(dfrm$values))   #  same list as you find in the Values section of ?hist

> dfrm$grp <- cut(dfrm$value, breaks=hist(dfrm$value)$breaks)

> dfrm
  value     grp
1    21 (20,30]
2    53 (50,60]
3     1  (0,10]
4    43 (40,50]
5    56 (50,60]
IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • Thanks, I have learned something about hist but I still don't get how to create the new (combined) data frame. When I say I am an R newbie I really mean it literally! – user1905389 Dec 14 '12 at 23:45
  • It's a bit of a PITA to recreate data objects. It's probably not as error prone in this particular instance, but it is rather error prone in general. Why not read how to use dput() to communicate efficiently and unambiguously, rather than implicitly expecting responders to reconstruct data objects? – IRTFM Dec 15 '12 at 00:34
0

Assuming your data.frame is called df, something like this should work.

bins <- c(0, 10, 20)

df$class <- findInterval(value, bins)
coatless
  • 20,011
  • 13
  • 69
  • 84