使用 IF 语句创建序数变量

Using an IF statement to create an ordinal variable

我是 R 的新手,对我的一个项目有疑问。

我有一个变量,Age.Range 来自导入的数据集 (od),关于药物过量。变量 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
> }

提前致谢!

这是您要找的吗?

# create a mock of your data
x <- c("15-19", "20-24", "25-29", "30-39", "40-49", "50-59", "60-69", "70-79")
od <- data.frame(Age.Range = sample(x, 100, replace = TRUE))


# create ageordinal
od$AgeOrdinal <- as.integer(factor(od$Age.Range))

od

请注意,这仅适用于因子水平(参见 levels(factor(od$Age.Range))已经排序。

如果您添加一个新级别,例如 9-14,这将无法按预期运行。 在这种情况下,您需要像这样更改代码:

# create a mock of your data
x <- c("9-14", "15-19", "20-24", "25-29", "30-39", "40-49", "50-59", "60-69", "70-79")
od <- data.frame(Age.Range = sample(x, 100, replace = TRUE))

# create ageordinal
od$AgeOrdinal <- as.integer(factor(od$Age.Range, levels = x, ordered = TRUE))

od

PS:当您创建 data.frame 时,R 已经将每个 char 列转换为因子。所以从技术上讲,在第一个例子中你不需要把它转换成一个因素。在第二个示例中,您必须调用函数 factor 因为您需要更改级别的顺序。