答案 0 :(得分:1)
一个选项是ifelse
df1$New <- with(df1, ifelse(weight <7, "a", ifelse(weight >=7 & weight < 8, "b", "c")))
df1$New
#[1] "a" "c" "c" "a" "c" "b" "c"
或者,如果有多个群组,我们可以使用cut
with(df1, as.character(cut(weight, breaks = c(-Inf, 7, 8, Inf),
labels = c('a', 'b', 'c'))))
#[1] "a" "c" "c" "a" "c" "b" "c"
set.seed(24)
df1 <- data.frame(weight = rnorm(7, 7, 3))
答案 1 :(得分:1)
您也可以使用dplyr替换相同的列(给它相同的名称)或添加(通过给它一个新名称)。下面的代码取代了现有的&#34;重量&#34;柱。
library(dplyr)
yourdata%>%mutate(
weight=ifelse(weight <7, "a", ifelse(weight >=7 & weight < 8, "b", "c")))
将来您可以提供一个可重现的数据示例,而不是jpeg:How to make a great R reproducible example?