目标是从height列创建一个新列,其中包含3个类:
我该怎么做?我试过了:
estudo[estudo$heigth<5,]$classheigth<-"baixo"
但它给出了错误。
"missing values are not allowed in sub scripted assignments of data frames"`
示例数据
# dput(head(estudo, 10))
estudo <- structure(list(height = c(2, 10, 20, 15, 3, 6.333333333, 7, 6, 3.4, 7)),
.Names = "height", row.names = c(NA, 10L), class = "data.frame")
答案 0 :(得分:0)
希望这有帮助!
estudo$class <- cut(estudo$height, c(0, 5, 10, Inf),
labels = c('low', 'medium', 'high'))
输出为:
height class
1 2.000000 low
2 10.000000 medium
3 20.000000 high
4 15.000000 high
5 3.000000 low
6 6.333333 medium
7 7.000000 medium
8 6.000000 medium
9 3.400000 low
10 7.000000 medium
示例数据:
estudo <- structure(list(height = c(2, 10, 20, 15, 3, 6.333333333, 7, 6, 3.4, 7)),
.Names = "height", row.names = c(NA, 10L), class = "data.frame")
答案 1 :(得分:0)
如果课程不是太多,你也可以这样做:
estudo$class[estudo$height < 5] <- "low"
estudo$class[estudo$height >= 5 & estudo$height <= 10] <- "medium"
estudo$class[estudo$height > 10] <- "high"
height class
1 2.000000 low
2 10.000000 medium
3 20.000000 high
4 15.000000 high
5 3.000000 low
6 6.333333 medium
7 7.000000 medium
8 6.000000 medium
9 3.400000 low
10 7.000000 medium