@
有朋友给我写信,问我R语言的问题,与其回复代码,不如写篇博客,顺便试试CSDN的新模板。
判断是否满足某个条件,然后返回相应的值。「比如:」
代码如下(示例):
if(x >= 22 & x <= 30){
return("A")
}
代码如下(示例):
test_f = function(x){
if(x >= 22 & x <= 30){
return("A")
}else if(x >=31 & x<=40){
return("B")
}else if(x >=41 & x <=50){
return("C")
}else if(x >=51 & x <=60){
return("D")
}else if(x >61 & x <=70){
return("E")
}
}
apply(dd,1,test_f)
dd = data.frame(age = c(22,23,24,35,36,37,45,46,47,56,57,65,67))
test_f = function(x){
if(x >= 22 & x <= 30){
return("A")
}else if(x >=31 & x<=40){
return("B")
}else if(x >=41 & x <=50){
return("C")
}else if(x >=51 & x <=60){
return("D")
}else if(x >61 & x <=70){
return("E")
}
}
apply(dd,1,test_f)
dd$status = apply(dd,1,test_f)
dd
「测试结果:」
> dd
age status
1 22 A
2 23 A
3 24 A
4 35 B
5 36 B
6 37 B
7 45 C
8 46 C
9 47 C
10 56 D
11 57 D
12 65 E
13 67 E
这是R语言的循环判断,是一个if函数的应用。
「更好的方法」可以用letters函数,进行自动赋值,而不用罗列全部的ABCDEFG,会智能一点。这里不再介绍。
阅读原文,体验更佳!
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有