0

I have to use the "ifelse" function in R to uncode values used in a variable.

The data frame being used is dance. The variable is Type. Via comments I have received, here is what I have:

ifelse(dance$Type=="Swg","Swing", 
ifelse(dance$Type=="Ldy","Lindy",
ifelse(dance$Type=="Blue","Blues",
else(dance$Type=="Contra","Contra"))))

I keep getting error messages. Are all of the commas correct? Also, did I end it correctly?

I keep getting error messages plus I'm supposed to specify the data frame I'm using somehow.

Any help would be greatly appreciated. Thank you.

divibisan
  • 11,659
  • 11
  • 40
  • 58
Vixxen81
  • 33
  • 1
  • 7
  • Please provide slightly more info. Depending on the class of Type you might be able to do this differently. – ekstroem Nov 22 '15 at 22:55
  • Type is a factor. Is that what you mean? – Vixxen81 Nov 22 '15 at 23:00
  • You have to nest your `ifelse` calls properly, like: `ifelse(dance$Type=="Swg","Swing", ifelse(dance$Type=="Ldy", "Lindy", NA ))` - Also, I'd consider using a lookup table as another possibility - http://stackoverflow.com/questions/18456968/how-do-i-map-a-vector-of-values-to-another-vector-with-my-own-custom-map-in-r – thelatemail Nov 22 '15 at 23:11

2 Answers2

1

If Type is a factor then you can rename the levels and extract them in this way (using f below):

f <- factor(c("Swg", "Ldy", "Blue", "Swg"))
# See the order of the levels by printing f. It's alphabetical
levels(f) <- c("Blues", "Lindy", "Swing")
as.character(f)

This will give

> f <- factor(c("Swg", "Ldy", "Blue", "Swg"))
> f
[1] Swg  Ldy  Blue Swg 
Levels: Blue Ldy Swg
> as.character(f)
[1] "Swg"  "Ldy"  "Blue" "Swg" 
> levels(f) <- c("Blues", "Lindy", "Swing")
> as.character(f)
[1] "Swing" "Lindy" "Blues" "Swing"
ekstroem
  • 5,957
  • 3
  • 22
  • 48
0

Thanks for your help. I figured it out via tips that were mentioned. I needed to name a dataframe and give an alternate solution for data not changed. I came up with:

Dance$new<-ifelse(dance$Type=="Swg","Swing", 
ifelse(dance$Type=="Ldy","Lindy",
ifelse(dance$Type=="Blue","Blues",
ifelse(dance$Type=="Contra","Contra",F))))
Vixxen81
  • 33
  • 1
  • 7