R语言 ifelse

在R语言中最简单的判断语句就是ifelse,用法很简单:

ifelse(
test, 
yes, 
no
)

举个例子:

> #查看已有数据集
> head(mycolon)
       name    mean    lower  upper
1       APM 0.32190  0.04071 0.6031
2 Apoptosis 0.07943 -0.17180 0.3307
3      ARG1 0.08682 -0.31810 0.4918
4   B Cells 0.14180 -0.12280 0.4063
5     B7-H3 0.76270  0.49930 1.0260
6      CD45 0.42830  0.09846 0.7582
> #根据lower和uper分组
> group <- ifelse(
+   mycolon$lower > 0, "up",
+   ifelse(
+     mycolon$upper < 0, "down",
+     "not"
+   )
+ )
> group#查看分组情况
 [1] "up"  "not" "not" "not" "up"  "up"  "up"  "not" "not" "not" "not" "not" "up"  "not" "not" "up"  "up"  "up"  "not"
[20] "up"  "up"  "up"  "not" "not" "not" "up"  "not" "up"  "not" "not" "not" "up"  "not" "up"  "up"  "not" "up"  "not"
[39] "not" "not" "up"  "up"  "not"
> #合并
> newdata <- data.frame(mycolon,group)
> head(newdata)
       name    mean    lower  upper group
1       APM 0.32190  0.04071 0.6031    up
2 Apoptosis 0.07943 -0.17180 0.3307   not
3      ARG1 0.08682 -0.31810 0.4918   not
4   B Cells 0.14180 -0.12280 0.4063   not
5     B7-H3 0.76270  0.49930 1.0260    up
6      CD45 0.42830  0.09846 0.7582    up

你可能感兴趣的:(r语言,开发语言)