重新编码字符变量
我正在尝试将字符变量重新编码为数值。
字符变量如下所示:
b <- c("Your category choice is correct", "Your category choice is incorrect", ...
我尝试了以下操作:
b_recoded <- ifelse(b = "Your category choice is correct",
c(1), c(0))
我收到以下错误:
未使用的参数(b =“您的类别选择是正确的”)
我怎样才能让它工作?我正在尝试将 “您的类别选择正确”
编码为 1
并将 “您的类别选择不正确”
编码为 0< /代码>。
抱歉问这个基本问题。我还在学习。
I'm trying to recode a character variable to a numeric value.
The character variable looks like this:
b <- c("Your category choice is correct", "Your category choice is incorrect", ...
I tried the following:
b_recoded <- ifelse(b = "Your category choice is correct",
c(1), c(0))
I get the following error:
unused argument(s) (b = "Your category choice is correct")
How can i get this to work? I'm trying to code "Your category choice is correct"
as 1
and "Your category choice is incorrect"
as 0
.
Sorry for the basic question. I'm still learning.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您的变量是字符,您可以使用正则表达式来匹配值:
If your variable is character, you can use regular expressions to match values:
ifelse
语句中的问题是您对逻辑表达式使用了单个等号。=
用于 R 中的顶级左赋值。在函数调用中,这意味着您将参数b
分配给“您的类别选择是正确的”.
要获得逻辑表达式,需要使用两个等号
==
。以下代码确实有效(使用 mropas 数据):另请注意,我省略了
c()
函数,因为您不需要组合单个元素。如果您刚开始使用 R,阅读一本介绍性手册或至少将其作为参考可能会很有用。这是我学习 R 时喜欢的一个:
http://cran. r-project.org/doc/contrib/Paradis-rdebuts_en.pdf
The problem in your
ifelse
statement is that you use a single equal sign for a logical expression.=
is used for top level left assignment in R. In a function call this means that you assign the argumentb
to"Your category choice is correct"
.To get a logical expression, you need to use two equal signs
==
. The following code does work (using mropas data):Also note that I omitted the
c()
functions as you don't need to combine single elements.If you are starting with R, it might be useful to read through one of the introductory manuals or at least keep it as reference. Here is one that I liked when I learned R:
http://cran.r-project.org/doc/contrib/Paradis-rdebuts_en.pdf
数据:
这会将您的
df
更改为factor
在开始时,因子的处理可能会有点混乱。因此,如果您更愿意将其保留为类
numeric
或integer
您可以这样做data:
This will change your
df
into afactor
In the beginning the handling of factors may get a bit confusing. So if you rather prefer to keep it as class
numeric
orinteger
you can e.g. do