【问题标题】:Grouping different values in a column and creating a new column in R (Similar to AS in SQL)在一列中对不同的值进行分组并在 R 中创建一个新列(类似于 SQL 中的 AS)
【发布时间】:2019-07-05 20:31:52
【问题描述】:

R 新手。过去一个小时左右,我一直在努力寻找我的问题的答案,但找不到,所以我会在这里问。我想将一些变量分组到一个列中并将其存储在一个新列中。我会尝试用一个例子更好地解释:

假设我有一个名为 Animals 的数据集。

Animal_type  Name
  Lion       Leo
  Tiger      Tigre
  Lion       Leon
  Dog        Rex
  Hyena      Sid

所以我基本上想做的是尝试将动物类型分组到更常见的组中,例如“大猫”。我正在使用 tidyverse,我已经尝试过了,但它没有用:

   Animals <- Animals %>% mutate(Species = ifelse('Animal_Type' == 
"Lion" | 'Animal_Type' == "Tiger", "Big_Cat", ifelse('Animal_Type' == 
"Dog" | 'Animal_Type' == "Hyena", "Big_Dog", "Other_Animal")))

但是,这不起作用并将所有内容更改为 Other_Animal。 animal_type 是类因素,但是在将 animal_type 的类更改为字符后,我尝试了这个问题并没有解决这个问题。这可能很容易,但非常感谢您的帮助。

【问题讨论】:

  • 你可以使用dplyr来完成它:library(dplyr)然后df %&gt;% mutate(Species = if_else(Animal_type %in% c("Lion", "Tiger"), "Big_Cat", if_else(Animal_type %in% c("Dog", "Hyena"), "Big_Dog", "Other_Animal")))

标签: r dataframe variables grouping aggregate


【解决方案1】:

R 对名称区分大小写。 在带有小“t”的数据“Animal_type”中,但在带有大写“T”的代码中。 并且在 mutate 中使用不带引号的变量。 所以以下代码有效:

Animals <- Animals %>% mutate(Species = ifelse(Animal_type ==  "Lion" | Animal_type == "Tiger", "Big_Cat", 
                                    ifelse(Animal_type ==   "Dog" | Animal_type == "Hyena", "Big_Dog", 
                                           "Other_Animal")))

【讨论】:

  • 我只是在这里做了一个例子。我用于我正在使用的原始数据的代码没有任何拼写错误。上述解决方案虽然有效:)
  • 很好,只是名字要小心:)
猜你喜欢
  • 1970-01-01
  • 2022-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-12
  • 2022-09-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多