dplyr的条件突变 [英] conditional mutate by dplyr
本文介绍了dplyr的条件突变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在我的数据集中创建一个新列:i)如果单词本身以"vi"开头,则删除最后一个字符;ii)如果单词本身不以"vi"开头,则删除最后两个字符.我知道如何在R中处理该问题,如下所示:
I want to create a new column in my dataset that: i) drop the last 1 character if the word itself starts with "vi"; and ii) drop the last 2 characters if the word itself does not start with "vi". I know how to work on that in R, like below:
iris$Species <- as.character(iris$Species)
iris$Species_mod <- substr(iris$Species,
1,
ifelse(grepl('^vi',iris$Species),
nchar(iris$Species)-1,
nchar(iris$Species)-2))
但是我很难在dplyr中破译 mutate
, if_else
和 matches
.谁能启发我?谢谢!
But I have a hard time in deciphering the mutate
, if_else
and matches
in dplyr. Can anyone enlighten me? Thanks!
推荐答案
相同的想法,只不过您明确需要将因子转换为字符串
Same idea, except you explicitly need to convert your factor to a string
iris = mutate(iris, Species_mod = substr(Species, 1, nchar(as.character(Species)) -
ifelse(grepl('^vi', Species), 1, 2)))
这篇关于dplyr的条件突变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文