用名称替换矢量值

时间:2016-06-21 07:19:42

标签: r replace

我试图用“冷”,“中”或“热”替换某些温度范围,我不知道如何解决我的问题。数据集命名为“stats”,温度为“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"))

我不断得到的错误是:

  

`$&lt; - 。data.frame replacement中的错误有1095行,数据有1092

我确实有几个NAs,但超过1095-1092 = 3个值

2 个答案:

答案 0 :(得分:3)

@ zx8754和@ N8TRO提供了很好的解决方案(尤其是cut)。这是另一个,具有可重复的例子。

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

答案 1 :(得分:3)

我们可以使用cut()并添加标签,如下所示:

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

注意,此结果列为factor,如果您需要它为character,那么我们需要将其包装到as.character()

相关问题