-1

我是 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
> }

先感谢您!

4

1 回答 1

0

这就是你要找的吗?

# 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,因为您需要更改级别的顺序。

于 2019-11-26T23:18:47.960 回答