[R] how to assign factor level into each value

jim holtman jholtman at gmail.com
Wed Dec 5 22:22:55 CET 2012


?cut

> x <- read.table(text = " Country                       Price
+ 1      CN                         44.25
+ 2      CN                         21.07
+ 3      CN                         92.70
+ 4      CN                         47.41
+ 5      CN                        111.67
+ 6      CN                         50.57", as.is = TRUE, header = TRUE)
> x$levels <- cut(x$Price, breaks = c(0,30,50,75,100,150,200,300,400,500,Inf))
> x
  Country  Price    levels
1      CN  44.25   (30,50]
2      CN  21.07    (0,30]
3      CN  92.70  (75,100]
4      CN  47.41   (30,50]
5      CN 111.67 (100,150]
6      CN  50.57   (50,75]
>
>


On Wed, Dec 5, 2012 at 7:26 AM, Tammy Ma <metal_licaling at live.com> wrote:
>
> HI, All
>
> I met the following problem. I dont know how to handle it.
>
>   Country                       Price
> 1      CN                         44.25
> 2      CN                         21.07
> 3      CN                         92.70
> 4      CN                         47.41
> 5      CN                        111.67
> 6      CN                         50.57
>
>
> I want to create the 3rd colume with different factor levels:
>  [1] "0-30"    "51-75"   "31-50"   "76-100"  "101-150" "151-200" "201-300" "500+"
>  [9] "301-400" "401-500"
>
> then the final result which I want is:
>
>   Country                       Price            levels
> 1      CN                         44.25          "31-50"
> 2      CN                         21.07          "0-30"
> 3      CN                         92.70         "76-100"
> 4      CN                         47.41           "31-50"
> 5      CN                        111.67        "101-150"
> 6      CN                         50.57         "51-75"
>
>
> How can I do this?
>
> Thanks.
>
> Tammy
>
>
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



-- 
Jim Holtman
Data Munger Guru

What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.




More information about the R-help mailing list