【问题标题】:Summarize with character type conditions in dplyr用 dplyr 中的字符类型条件进行总结
【发布时间】:2018-07-19 10:04:34
【问题描述】:

我想计算一个国家单独列出的次数,以及与其他国家一起列出的次数。

这是我的数据集的一部分:

address_countries2
name_countries      n_countries
China               1                      
China               1
Usa                 1                        
Usa                 1
China France        2               
China France        2
India               1                      
India               1
Jordan Germany      2             

我已经使用下面的代码来提取每个国家出现的次数。

publication_countries <- address_countries2 %>% 
  select(name_countries, n_countries) %>% 
  unnest_tokens(word, name_countries) %>%
  group_by(word) %>% 
  summarise(TP = n())

 head(publication_countries)
 # A tibble: 6 x 2
    word          TP
    <chr>       <int>
   1 China         4
   2 Usa           2
   3 France        2
   4 India         2
   5 Jordan        1       
   6 Germany       1

我想创建一个新列,其中包含一个国家/地区单独列出的行数,以及第二个列,其中包含一个国家/地区与其他国家/地区一起列出的次数。

期望的输出 像这样的:

 head(publication_countries)
 # A tibble: 6 x 2
    word          TP      single_times      with_other_countries
    <chr>       <int>            <int>                     <int>   
   1 China         4                2                         2
   2 Usa           2                2                         0
   3 France        2                0                         2
   4 India         2                2                         0
   5 Jordan        1                0                         1
   6 Germany       1                0                         1

link 我看到了一种可能的方法来用条件进行总结,但是,在我的情况下,我需要使用不同于 sum() 的东西,因为我的条件对象是字符形式的(列字)。

summarise(TP = n() , IP = count(word[n_countries=="1"])) 

但我得到这个错误:

Error in summarise_impl(.data, dots) : 
  Evaluation error: no applicable method for 'groups' applied to an object of    class "character"

任何帮助将不胜感激:)

非常感谢

【问题讨论】:

    标签: r dplyr summarize


    【解决方案1】:
    dat%>% 
       select(name_countries, n_countries) %>% 
       unnest_tokens(word, name_countries) %>%
       group_by(word)%>%mutate(TP=n())%>%
       group_by(n_countries,word)%>%mutate(Tp1=n())%>%
       unique()%>%spread(n_countries,Tp1,0)
    # A tibble: 6 x 4
    # Groups:   word [6]
         word    TP   `1`   `2`
    *   <chr> <int> <dbl> <dbl>
    1   china     4     2     2
    2  france     2     0     2
    3 germany     1     0     1
    4   india     2     2     0
    5  jordan     1     0     1
    6     usa     2     2     0
    

    【讨论】:

    • 只有一个小问题。在我的完整数据样本中,n_countries 的值从 1 到 3 不等,通过 n_countries 摸索给了我三列。有没有办法组合任何不统一的列?
    • 对不起,我不明白你的问题
    • 有时“name_countries”中有两个以上的国家,例如当 3 个国家 n_countries = 3 时。使用您的代码时,这给了我三列。但我只想要两列,一列用于所有单个国家,另一列用于任意数量的国家。
    • 不可能mutate所有需要组合在一起的列,即将它们加在一起得到一列吗?
    猜你喜欢
    • 2020-03-30
    • 2020-02-07
    • 2017-09-14
    • 2021-06-30
    • 1970-01-01
    • 2019-07-16
    • 1970-01-01
    • 2016-07-26
    • 1970-01-01
    相关资源
    最近更新 更多