根据条件将变量从数值型变为字符型的突变

huangapple go评论62阅读模式
英文:

variable mutation from numeric to character according to a condition

问题

在我的数据框中,我有一个数值列 var1。在该列中,所有小于或等于30的值,我想将其变为 "<=30",并且变量类型应为字符型。

这段代码确实识别出小于30的值,并返回TRUE或FALSE。

Mydata <- Mydata %>%
  select("var1") %>%
  mutate(less_than_30 = (var1 <= 30))

使用这个笨拙的代码,我试图将TRUE转换为 "<=30",但不起作用,因为它报错 不能将 <character> 转换为 <logical>。,虽然我认为应该是 <logical> 转换为 <character>

Mydata["less_than_30"][Mydata["less_than_30"] == "TRUE"] <- "&lt;=30"

我确信有一种方便的方法可以做到这一点。你能帮忙吗?

英文:

In my data frame I have a numeric column var1. In that column, all the values that are 30 or less, I want to have as "<=30" and the variable type should be character.

This code sure recognizes values less than 30, and that results either TRUE or FALSE.

Mydata &lt;- Mydata %&gt;% select(
    &quot;var1&quot;) %&gt;%
  mutate(less_than_30 = (var1 &lt;= 30))

With this clumsy code I tried to transform TRUE's into "<=30", but that doesn't work because ! Can&#39;t convert &lt;character&gt; to &lt;logical&gt;., though I think it should read &lt;logical&gt; to &lt;character&gt;

Mydata[&quot;less_than_30&quot;][Mydata[&quot;less_than_30&quot;] == &quot;TRUE&quot;] &lt;- &quot;&lt;=30&quot;

I'm sure there is a handy way to do this. Can you help?

答案1

得分: 0

请尝试

```r
Mydata <- Mydata %>%
  select(
    "var1"
  ) %>%
  mutate(less_than_30 = ifelse(var1 <= 30, '<=30', NA))
英文:

Please try

Mydata &lt;- Mydata %&gt;% select(
    &quot;var1&quot;) %&gt;%
  mutate(less_than_30 = ifelse(var1 &lt;= 30,&#39;&lt;=30&#39;,NA))

huangapple
  • 本文由 发表于 2023年7月3日 23:17:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76606082.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定