R 用名称替换向量值
我试图用“冷”、“中”或“热”来代替某些温度范围,但我不知道如何解决我的问题。数据集名为“stats”,温度名为“temp1”R 用名称替换向量值,r,replace,R,Replace,我试图用“冷”、“中”或“热”来代替某些温度范围,但我不知道如何解决我的问题。数据集名为“stats”,温度名为“temp1” tmp1@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
tmp1@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
set.seed(357)
xy我们可以使用cut()
并添加标签,如下所示:
stats$temp2 <- cut(stats$temp1, c(0, 11, 22, Inf), labels = c("cold", "med", "hot"))
stats$temp2欢迎来到堆栈溢出!请阅读相关信息以及如何给出建议。这将使其他人更容易帮助您。stats
是一个包的名称,因此我不会将其用作变量名。但是如果您坚持:stats$temp2可能会被削减?:stats$temp2非常感谢!!!我希望我能给你烤饼干!!或者,您可以用“ok”初始化feel
,然后为cold
和hotwothot
@docendodiscimus true执行两个子赋值,但我想这样做是为了在不考虑任何值的情况下让NAs进行健全性检查。
stats$temp2 <- cut(stats$temp1, c(0, 11, 22, Inf), labels = c("cold", "med", "hot"))