Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在R中合并我的df中不太相关的行?_R_Dplyr_Rows_Linux Df - Fatal编程技术网

如何在R中合并我的df中不太相关的行?

如何在R中合并我的df中不太相关的行?,r,dplyr,rows,linux-df,R,Dplyr,Rows,Linux Df,这是我的df: col1 col2 1 a 20% 2 b 20% 3 c 15% 4 d 10% 5 e 9% 6 f 8% 7 g 7% 8 h 6% 9 h 5% 我想要这样的东西 col1 col2 1 a 20% 2 b 20% 3 c 15% 4 d

这是我的df:

  col1 col2 
1   a    20%  
2   b    20% 
3   c    15% 
4   d    10% 
5   e     9%  
6   f     8%  
7   g     7%  
8   h     6%  
9   h     5%  
我想要这样的东西

     col1    col2 
1       a     20%  
2       b     20% 
3       c     15% 
4       d     10% 
5   other     35% 


我尝试使用dplyr来解决这个问题,但没有成功。

您可以使用forcats包中的
fct\u collapse()

library(tidyverse)

df <- tribble(
  ~col1, ~col2,
  "a", 20,
  "b", 20,
  "c", 15,
  "d", 10, 
  "e", 9,  
  "f", 8,  
  "g", 7,  
  "h", 6,  
  "h", 5
  )

df$col1 <- fct_collapse(
  df$col1,
  a = "a",
  b = "b",
  c = "c",
  d = "d",
  other_level = "other")

df %>%
  group_by(col1) %>%
  summarise(col2 = sum(col2))
库(tidyverse)
df%
总结(col2=总和(col2))