如何根据R中另一列的特定值正确更改级别值?
我想根据同一列的特定值和另一列的特定值更改/重新编码列的级别。例如,让我们使用ggplot2 ::钻石。在这种情况下,我想在 剪切 列中更改“ premium”的价值,如果列 color 是“ d”,如果列 color 是“ j”,则将“ prem”的值更改为“惊人”。这是我的尝试:
df <- ggplot2::diamonds
unique(df$cut) #to look at the initial values
df$cut <- with(df,ifelse(cut == "Premium" & color == "D", "Perfect",
ifelse(cut== "Premium" & color == "J","Amazing", cut)))
问题是,随后查看剪切列时,其他值也已更改。
unique(df$cut)
[1] "5" "4" "2" "3" "1" "Perfect" "Amazing"
有人可以告诉我我在这里做错了什么吗?如果除了我尝试这样做之外还有其他方法,我也很感谢您看到这一点!
I want to change/recode the levels for a column based on a specific value of the same column and another column. As an example, let's use ggplot2::diamonds. In this scenario, I want to change the value of "Premium" in the cut column to "Perfect" if the column color is "D" and change the value of "Premium" to "Amazing" if column color is "J". This is my attempt:
df <- ggplot2::diamonds
unique(df$cut) #to look at the initial values
df$cut <- with(df,ifelse(cut == "Premium" & color == "D", "Perfect",
ifelse(cut== "Premium" & color == "J","Amazing", cut)))
The issue is that when looking at the cut column afterwards, the other values have also been changed.
unique(df$cut)
[1] "5" "4" "2" "3" "1" "Perfect" "Amazing"
Can someone please tell me what I am doing wrong here? If there are other ways than how I attempted to do this, I would also appreciate seeing that as well!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
case_when()
:输出:
Using
case_when()
:Output:
我经常使用此
base
r方法:但是您必须先将因子转换为字符,否则您会遇到错误。
I often use this
base
R method:But you have to turn your factor to character first, or you will get an error.