1

I have a set of data that I am importing from a csv

info <- read.csv("test.csv")

here is an example of what it would look like

  name   type   purchase
1 mark   new    yes
2 steve  old    no
3 jim    old    yes
4 bill   new    yes

What I want to do:

I want to loop through the purchase column and change all the yes's to True & no's to be False. Then loop through the type column and change all the old's to customer.

I've tried to mess with all the different apply's and couldnt get it to work. Also Ive tried a bunch of the methods in this thread Replace a value in a data frame based on a conditional (`if`) statement in R but still no luck.

Any help or guidance would be much appreciated!

Thanks, Nico

Community
  • 1
  • 1
NicoM
  • 629
  • 2
  • 6
  • 22
  • To improve your quality of learning, please show what you have tried that didn't work. Others might be able to point you in the right direction to fix your code rather than just answering your question for you. Having offered an answer to your question, I tried the answers at the linked question and had no problem applying them to your situation. – A5C1D2H2I1M1N2O1R2T1 Sep 14 '13 at 05:57
  • Thanks and will do in the future. I was trying all the solutions with levels() and it was giving me weird errors but next time will be more thorough. – NicoM Sep 18 '13 at 13:32

1 Answers1

5

Here's an approach using within, basic character substitution, and basic tests for character equivalence.

within(mydf, {
  type <- gsub("old", "customer", type)
  purchase <- purchase == "yes"
})
#    name     type purchase
# 1  mark      new     TRUE
# 2 steve customer    FALSE
# 3   jim customer     TRUE
# 4  bill      new     TRUE

I've used gsub to replace "type", but there are other approaches that can be taken (eg factor, ifelse, and so on).

A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485