英文:
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"] <- "<=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 <- Mydata %>% select(
"var1") %>%
mutate(less_than_30 = (var1 <= 30))
With this clumsy code I tried to transform TRUE's into "<=30", but that doesn't work because ! Can't convert <character> to <logical>.
, though I think it should read <logical> to <character>
Mydata["less_than_30"][Mydata["less_than_30"] == "TRUE"] <- "<=30"
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 <- Mydata %>% select(
"var1") %>%
mutate(less_than_30 = ifelse(var1 <= 30,'<=30',NA))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论