R中需要数字时如何计算字符串?

发布于 2025-01-19 09:13:46 字数 435 浏览 0 评论 0原文

我想将数字更改为因子,但我的因子级别以字符串形式给出,而函数因子需要数字。如何将其转换为数字或评估字符串?示例:

给定:

a = c(0,1,1,1,0,1,0)

lev = 'c(0,1)' 

lab = c('firstlev','secondlev') # this is irrelevant to question.

想要:

factor(a,levels = lev labels = lab)

我可以明确地编写级别,但我有一个大循环,并且正在从另一个文件自动读取因子级别。我尝试了 quo、!!、eval 和朋友,但我完全不知道什么是正确的方法,甚至我应该寻找什么,从字符串到数字的转换,或者字符串的评估类型。

I want to change a numeric into a factor, but my factor level is given as a character string while the function factor needs a numeric. How do I convert it into a numeric or evaluate the character string? Example:

given:

a = c(0,1,1,1,0,1,0)

lev = 'c(0,1)' 

lab = c('firstlev','secondlev') # this is irrelevant to question.

wanted:

factor(a,levels = lev labels = lab)

I could write the levels explicitly, but I have a big loop and am reading the factor levels automatically from another file. I tried quo, !!, eval and friends, but I am totally lost as to what is the right way to do and even what I should be looking for, conversion from string to numeric, or for a type of evaluation of a string.

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苦笑流年记忆 2025-01-26 09:13:46

怎么样:

a = c(0,1,1,1,0,1,0)

lev = 'c(0,1)' 

lab = c('firstlev','secondlev') # this is irrelevant to question.

factor(a,levels = eval(parse(text=lev)), labels = lab)
#> [1] firstlev  secondlev secondlev secondlev firstlev  secondlev firstlev 
#> Levels: firstlev secondlev

reprex 包 (v2.0.1) 创建于 2022 年 4 月 4 日< /sup>

How about this:

a = c(0,1,1,1,0,1,0)

lev = 'c(0,1)' 

lab = c('firstlev','secondlev') # this is irrelevant to question.

factor(a,levels = eval(parse(text=lev)), labels = lab)
#> [1] firstlev  secondlev secondlev secondlev firstlev  secondlev firstlev 
#> Levels: firstlev secondlev

Created on 2022-04-04 by the reprex package (v2.0.1)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文