这个问题是在研究这个问题时出现的.

I have this manipulated iris dataset with two vectors:

new_name <- c("new_setoas", "new_virginica")
to_select <- c("setosa", "virginica")
iris %>% 
  group_by(Species) %>% 
  slice(1:2) %>% 
  mutate(Species = as.character(Species))

  Sepal.Length Sepal.Width Petal.Length Petal.Width Species   
         <dbl>       <dbl>        <dbl>       <dbl> <chr>     
1          5.1         3.5          1.4         0.2 setosa    
2          4.9         3            1.4         0.2 setosa    
3          7           3.2          4.7         1.4 versicolor
4          6.4         3.2          4.5         1.5 versicolor
5          6.3         3.3          6           2.5 virginica 
6          5.8         2.7          5.1         1.9 virginica

我想用另一个向量(new_name)中的值替换从一个向量(to_select)中 Select 的物种中的值

When I do:

new_name <- c("new_setoas", "new_virginica")
to_select <- c("setosa", "virginica")
iris %>% 
  group_by(Species) %>% 
  slice(1:2) %>% 
  mutate(Species = as.character(Species)) %>% 
  mutate(Species = ifelse(Species %in% to_select, new_name, Species))

# I get:

  Sepal.Length Sepal.Width Petal.Length Petal.Width Species      
         <dbl>       <dbl>        <dbl>       <dbl> <chr>        
1          5.1         3.5          1.4         0.2 new_setoas   
2          4.9         3            1.4         0.2 **new_virginica** # should be new_setoas
3          7           3.2          4.7         1.4 versicolor   
4          6.4         3.2          4.5         1.5 versicolor   
5          6.3         3.3          6           2.5 **new_setoas** # should be new_virginica   
6          5.8         2.7          5.1         1.9 new_virginica 

虽然我知道这是因为recycling.我不知道该怎么避免这件事!

推荐答案

我们可以使用recode-可以在group_by步骤本身完成,而不是分组,然后修改GROUP列

library(dplyr)
iris %>% 
  group_by(Species =  recode(as.character(Species),
     !!!setNames(new_name, to_select))) %>% 
  slice(1:2) 

-输出

# A tibble: 6 × 5
# Groups:   Species [3]
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species      
         <dbl>       <dbl>        <dbl>       <dbl> <chr>        
1          5.1         3.5          1.4         0.2 new_setoas   
2          4.9         3            1.4         0.2 new_setoas   
3          7           3.2          4.7         1.4 versicolor   
4          6.4         3.2          4.5         1.5 versicolor   
5          6.3         3.3          6           2.5 new_virginica
6          5.8         2.7          5.1         1.9 new_virginica

R相关问答推荐

行式dppr中的变量列名

基于现有类创建类的打印方法(即,打印tibles更长时间)

R:连接值,而不是变量?

有没有一种方法可以从函数中创建一个值的列表,然后将这些值变成R中的直方图?我一直觉得不行

用相同方法得到不同函数的ROC最优截断值

将嵌套列表子集化为嵌套列表

在另存为PNG之前隐藏htmlwidget绘图元素

如何编辑gMarginal背景以匹配绘图背景?

如何根据嵌套元素的名称高效而优雅地确定它属于哪个列表?

有效识别长载体中的高/低命中

汇总数据的Sheffe检验的P值(平均值和标准差)

在R中创建连续的期间

有没有可能用shiny 的书签恢复手风琴面板?

将多个变量组合成宽格式

减go R中列表的所有唯一元素对

Rmarkdown::Render vs Source()

如何在Quarto中使用美人鱼图表中的标记来加粗文本

如何在R中创建这些列?

重写时间间隔模糊连接以减少内存消耗

为哑铃图准备日期数据