-1

I have a data frame "books" with a numeric variable "price." I want to create a new factor variable called "affordable" with two levels: "yes" and "no." When price is greater than 100, affordable is equal to "no." When price is less than 100, affordable is equal to "yes." How do I create this variable and add it to my data frame?

This is where I'm stuck:

books$affordable <- ifelse(books$price > 100, "no", "yes")
Jaap
  • 81,064
  • 34
  • 182
  • 193
user9476687
  • 11
  • 1
  • 4
  • What have you done till now? Please share your code. – MKR Mar 11 '18 at 21:13
  • 1
    Some clues to get you started: `?ifelse` and `?factor`. And you'll need to decide how to handle the case where `price` equals 100. – neilfws Mar 11 '18 at 21:15
  • Your price is way to high you need to cut it... them bricks is way to hot you need to... `cut()` it – De Novo Mar 11 '18 at 21:17
  • Welcome to StackOverflow! Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610). This will make it much easier for others to help you. – Jaap Mar 11 '18 at 21:18
  • or. actually, `split()` it, since you want it according to a logical test, rather than some distribution.. but i can't think of a good song for that. – De Novo Mar 11 '18 at 21:20
  • 1
    This is where I'm stuck: books$affordable <- ifelse(books$price > 100, "no", "yes") – user9476687 Mar 11 '18 at 21:24
  • 1
    put that up in the body of your question :) – De Novo Mar 11 '18 at 21:26

1 Answers1

0

OPs initial code:

books$affordable <- ifelse(books$price > 100, "no", "yes") 

This should produce a character vector, with "no" for cases where the test evaluates to TRUE, i.e., it's expensive, and "yes" otherwise. Unless you're not telling us something about your data:

class(books$affordable)
# [1] "character"

You want a factor. So do this:

books$affordable <- factor(ifelse(books$price > 100, "no", "yes")) 

Check

class(books$affordable)
levels(books$affordable)

Note that your levels will be ordered with "no" first, and "yes" second. That may be what you want, but may not.

De Novo
  • 7,120
  • 1
  • 23
  • 39