【发布时间】:2019-11-26 21:59:51
【问题描述】:
我是 R 新手,有一个关于我的项目的问题。
我有一个来自导入数据集 (od) 的关于药物过量的变量 Age.Range。变量 Age.Range 包含以下级别:
15-19, 20-24, 25-29, 30-39, 40-49, 50-59, 60-69, 70-79
我想创建一个新的表示 Age.Range 的有序变量,这样 15-19 将表示为 1,20-24 将表示为 2,25-29 将表示为 3,依此类推以此类推。
在 SAS 中,我的代码如下所示:
if Age.Range="15-19" then AgeOrdinal=1;
else if Age.Range="20-24" then AgeOrdinal=2
if Age.Range="20-24" then AgeOrdinal=3;
else if Age.Range="24-29" then AgeOrdinal=4
if Age.Range="30-39" then AgeOrdinal=5;
else if Age.Range="40-49" then AgeOrdinal=6
etc.
我可以在 R 中做类似的事情吗?如果是这样,怎么做?谢谢!
P.S.,我知道如何创建像
这样的虚拟变量od$SurviveYes <- ifelse(od$Survive=="Y", 1, 0)
但我想要一个具有两个以上级别的变量。
到目前为止,这是我糟糕的尝试:
> od$AgeOrdinal <- c()
> age <- function(od$Age.Range){
> sapply(od$Age.Range, function(x) if(x == "15-19") 1
+ else if (x == "20-24") 2
+ else if (x == "25-29") 3
+ else if (x == "30-39") 4
+ else if (x == "40-49") 5
+ else if (x == "50-59") 6
+ else if (x == "60-69") 7
+ else (x == "70-79") 8
> }
提前谢谢你!
【问题讨论】:
-
as.integer(factor(od$Age.Range)) 怎么样?
-
od$AgeOrdinal <- match(od$Age.Range, unique(od$Age.Range))