首页 > 解决方案 > pivot_wider:如何为非唯一值添加行?

问题描述

我有一个长格式的表格,其中包含不同语言的物种名称和 2 级 id 编号,一个对应于该物种,另一个对应于该物种的不同名称。

例如:

species_list <- cbind.data.frame(num_sp= c(100,101,101,101,101,102,102,103), num_name = c(1,1,2,3,4,1,2,1), language=c("latin","latin", "english", "english", "english","latin","english","english"), name=c("marinus thingus", "aquaticus stuffae", "blob","water being","marine creature","altermarinus stuffae","other marine stuff", "unknown thingy"))

  num_sp num_name language                 name
1    100        1    latin      marinus thingus
2    101        1    latin    aquaticus stuffae
3    101        2  english                 blob
4    101        3  english          water being
5    101        4  english      marine creature
6    102        1    latin altermarinus stuffae
7    102        2  english   other marine stuff
8    103        1  english       unknown thingy

我想要一个对应表,以便能够从英文名称中获取拉丁名称。我认为该表应该给我列中的语言,并且只有行中的 num_sp id,这对应于 i 的事情 a pivot_wider,除了我的“num_sp”不是唯一标识符,所以该函数给出警告:

Warning message:
Values are not uniquely identified; output will contain list-cols.

有没有办法(通过 values_fn,也许?)将这些列表列拆分为不同的行,得到一个像这样的表:

 num_sp            english                latin
1    100               <NA>      marinus thingus
2    101               blob    aquaticus stuffae
3    101        water being    aquaticus stuffae
4    101    marine creature    aquaticus stuffae
5    102 other marine stuff altermarinus stuffae
6    103     unknown thingy                 <NA>

谢谢你的时间!

标签: rduplicatestidyr

解决方案


这将解决问题

species_list %>% pivot_wider(id_cols = num_sp, 
                             names_from = language, 
                             values_from = name, 
                             values_fn = list) %>%
  unnest(-num_sp)

# A tibble: 6 x 3
  num_sp latin                english           
   <dbl> <chr>                <chr>             
1    100 marinus thingus      NA                
2    101 aquaticus stuffae    blob              
3    101 aquaticus stuffae    water being       
4    101 aquaticus stuffae    marine creature   
5    102 altermarinus stuffae other marine stuff
6    103 NA                   unknown thingy    

推荐阅读