1

I have the following data frame in R.

data<-data.frame(Outlook=c("Sunny","Sunny","Overcast","Rainy","Rainy","Rainy",    "Overcast", "Sunny") )

but i need to change it to assign an integer to each value (make it factor). So, i run:

ordered(as.character(data$Outlook),
levels = c(100,50, 30),
labels = c("Overcast", "Rainy", "Sunny"))

But it makes all NA for me

<NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA> <NA>
Levels: Overcast < Rainy < Sunny

So, how can i stop it from making NAs?

I have seen this, but didn't help me

Sal-laS
  • 11,016
  • 25
  • 99
  • 169
  • 1
    The levels should respond to unique values you see in your data (and potentially more values) – talat Apr 11 '17 at 13:16
  • 1
    I don't think we need factor, maybe use lookup? `data$OutlookN <- setNames(c(100, 50, 30), c("Overcast", "Rainy", "Sunny"))[data$Outlook]` – zx8754 Apr 11 '17 at 13:21
  • 1
    If you really want an ordered factor, `ordered(data$Outlook)` or `ordered(data$Outlook, levels=rev(levels(data$Outlook)))` will work with reversed orders. – lmo Apr 11 '17 at 13:26

1 Answers1

3

Thanks to the @zx8754

outlook<-setNames(c(100, 50, 30), c("Overcast", "Rainy", "Sunny"))[data$Outlook]

solved the problem

Sal-laS
  • 11,016
  • 25
  • 99
  • 169
  • Click on edit, then you will see a tiny checkbox on the right bottom. – zx8754 Apr 11 '17 at 13:30
  • I will make it, but what about this case `setNames(c(100, 50), c(TRUE,FALSE))[data$Windy]` – Sal-laS Apr 11 '17 at 13:31
  • 1
    Anyway, my comment about wiki was simply - "avoid copy pasting my comment as your own answer". – zx8754 Apr 11 '17 at 13:32
  • @zx8754 if u don't like it, i can remove it, and i will accept ur answer, but u didn't write any answer, and i think, it is more readable for other people if they see an answer – Sal-laS Apr 11 '17 at 13:36
  • 1
    I used comment to clarify the expected output, as you were asking about factors, and I suggested using lookups. It is OK and encouraged to convert comments to answers, but not as fast :) Keep as it is, expand with the final solution. I don't mind. – zx8754 Apr 11 '17 at 13:39