R语言 从一个变量中筛选分数并将其放入新变量中

ubof19bj  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(150)

所以我有这个变量测试分数是编码的规模从1-9。我必须采取那些谁的分数1-3低,4-6好,7-9高的新变量。然后必须作出一个新的变量,比较低和高,一个变量比较低和好。

test_scores<- c(sample(1:10, 122, replace = TRUE)

test_scores<-as.data.frame(test_scores)
low<- filter(test_scores,test_scores1 > 3)
high<- filter(test_scores, test_scores< 7)
good<-filter(test_scores,test_scores== 4:6)

但新变量中的N不计数到122

我想到使用if函数:

low<- ifelse(test_scores$test_scores == 1:3 , 1:3 , 0)
mods<- ifelse(test_scores$test_scores == 4:6, 4:6, 0) 
high<- ifelse(test_scores$test_scores == 7:9, 7:9, 0)

但是有些分数没有过滤,而是变成0,即使分数匹配。有什么想法吗?

cngwdvgl

cngwdvgl1#

您可以使用“cut”来生成新的bin:

set.seed(123)
test_scores <- sample(1:9, 122, T)
test_scores
#>   [1] 3 3 2 6 5 4 6 9 5 3 9 9 9 3 8 7 9 3 4 1 7 5 7 9 9 7 5 7 5 6 9 2 5 8 2 1 9
#>  [38] 9 6 5 9 4 6 8 6 6 7 1 6 2 1 2 4 5 6 3 9 4 6 9 9 7 3 8 9 3 7 3 7 6 5 5 8 3
#>  [75] 2 2 6 4 1 6 3 8 3 8 1 7 7 7 6 7 5 6 8 5 7 4 3 9 7 6 9 7 2 3 8 4 7 4 1 8 4
#> [112] 9 8 6 4 8 3 4 4 6 1 4

cuts <- cut(test_scores, c(0,3,6,9), labels = F)
cuts
#>   [1] 1 1 1 2 2 2 2 3 2 1 3 3 3 1 3 3 3 1 2 1 3 2 3 3 3 3 2 3 2 2 3 1 2 3 1 1 3
#>  [38] 3 2 2 3 2 2 3 2 2 3 1 2 1 1 1 2 2 2 1 3 2 2 3 3 3 1 3 3 1 3 1 3 2 2 2 3 1
#>  [75] 1 1 2 2 1 2 1 3 1 3 1 3 3 3 2 3 2 2 3 2 3 2 1 3 3 2 3 3 1 1 3 2 3 2 1 3 2
#> [112] 3 3 2 2 3 1 2 2 2 1 2

如果希望每个bin都有一个变量,否则为零,则必须使用%in%,而不是==

low<- ifelse(test_scores$test_scores %in% 1:3 , test_scores$test_scores , 0)
mods<- ifelse(test_scores$test_scores %in% 4:6, test_scores$test_scores, 0) 
high<- ifelse(test_scores$test_scores %in% 7:9, test_scores$test_scores, 0)

相关问题