我是 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 中做类似的事情吗?如果是这样,怎么做?谢谢!
PS,我知道如何创建一个虚拟变量
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
> }
先感谢您!