-1

I'm trying to replace certain temperature ranges with either "cold", "med", or "hot", and I don't know how to fix my problem. Dataset is named "stats" and temperature is "temp1".

tmp1<-stats$temp1
lesser<-stats[stats$temp1<=11,]
inbetween<-stats[stats$temp1>11 & stats$temp1<22,]
greater<-stats[stats$temp1>=22,]
stats$temp2<-replace(tmp1, c("lesser", "inbetween", "greater"), c("cold","med","hot"))

The error I keep getting is:

Error in `$<-.data.frame replacement has 1095 rows, data has 1092

I do have several NAs, but more than 1095-1092= 3 values

zx8754
  • 52,746
  • 12
  • 114
  • 209
Brooke
  • 9
  • 2
    Welcome to Stack Overflow! 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). This will make it much easier for others to help you. – zx8754 Jun 21 '16 at 07:21
  • `stats` is the name of a package, so I wouldn't use that as a variable name. – N8TRO Jun 21 '16 at 07:34
  • But if you insist: `stats$temp2 <- ifelse(stats$temp1<=11, "cold", ifelse(stats$temp1>=22, "hot","med"))` – N8TRO Jun 21 '16 at 07:36
  • 1
    Maybe cut?: `stats$temp2 <- cut(stats$temp1, c(0, 11, 22, Inf), labels = c("cold","med","hot"))` – zx8754 Jun 21 '16 at 07:39
  • 1
    Thank you so much!!! I wish I could bake you cookies!! – Brooke Jun 21 '16 at 07:40
  • In StackOverflow world cookies are made of upvotes and [tickmarks](http://stackoverflow.com/help/accepted-answer). – zx8754 Jun 21 '16 at 10:25

2 Answers2

3

@zx8754 and @N8TRO provide nice solutions (especially cut). Here's another one, with a reproducible example.

set.seed(357)
xy <- data.frame(temp = sample(0:50, size = 30, replace = TRUE))

xy[xy$temp <= 10, "feel"] <- "cold"

xy[xy$temp > 10 & xy$temp < 30, "feel"] <- "ok"

xy[xy$temp >= 30, "feel"] <- "hothothot"

> head(xy)
  temp      feel
1    5      cold
2    2      cold
3   14        ok
4   11        ok
5   33 hothothot
6   23        ok
Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
  • 1
    Alternatively, you could initialize `feel` with "ok" and then do two sub-assignments for `cold` and `hothothot` – talat Jun 21 '16 at 08:02
  • 1
    @docendodiscimus true, but I wanted to do it this way to have any NAs for sanity-check in case any value is not being considered. – Roman Luštrik Jun 21 '16 at 09:57
3

We can use cut() and add labels as below:

stats$temp2 <- cut(stats$temp1, c(0, 11, 22, Inf), labels = c("cold", "med", "hot"))

Note that this resulting column is factor, if you need it to be a character then we will need to wrap it into as.character().

zx8754
  • 52,746
  • 12
  • 114
  • 209