通过保证代码顺序将字符转换为因素

发布于 2025-02-11 20:09:57 字数 602 浏览 4 评论 0 原文

我正在处理包含二进制变量的数据,这些变量被编码为字符。有一次,我将它们转换为因素。

在另一点,我必须将它们转换为数字,并处理数字的值。基本上,我正在做类似于 ARM 软件包中的重新缩放的事情,并且我需要两个类别的数值值,因此我可以计算一个均值。我不在乎两个值,但是一旦使用它们,我需要每个数据的值相同的值。

例如,如果我将编码为“ y”和“ n”的变量“ ikt”,并且我一次运行代码,我可能会这样做

ikt <- c("y", "n", "n", "n") 
ikt.factor <- as.factor(ikt) 
ikt.num <- as.numeric(ikt.factor)

,现在我运行了它,我得到了 ikt.num 要包含 2,1,1,1

问题是,如何让R始终创建相同的转换,而永远不要 1,2,2,2 ?我需要与数据集和环境独立发生,只要我能保证“ IKT”​​列将始终将其编码为“ Y”和“ N”。

我不想将可变级别对数字的对应关系进行硬编码,因为此代码必须对不同的二进制变量进行一定的工作,这可以使用不同的字符代码到达。

I am dealing with data that includes binary variables, which arrive coded as characters. At one point, I convert them to factors.

At a different point, I have to convert them to numbers, and deal with the numbers' value. Basically, I am doing something very similar to the rescaling in the arm package, and I need two numerical values for the two categories, so I can calculate a mean. I don't care that much which two values, but once they have been used, I need the same values for each batch of data.

For example, if I have the variable "ikt" coded as "y" and "n", and I run my code once, I may do

ikt <- c("y", "n", "n", "n") 
ikt.factor <- as.factor(ikt) 
ikt.num <- as.numeric(ikt.factor)

and now that I ran it, I got ikt.num to contain 2,1,1,1.

The question is, how can I get R to always create the same conversion, and never 1,2,2,2? I need this to happen independently of the dataset and the environment, as long as I can guarantee that the "ikt" column will always arrive coded as "y" and "n".

I don't want to have to hardcode the correspondence of variable levels to numbers, since this code has to work generically for different binary variables, which can arrive with different character codes.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文