重新排列行以匹配另一个数据框

时间:2018-12-08 17:08:50

标签: r

我有一个数据框,其中包含纬度,经度和物种名称作为变量,具有16个观测值。

# A tibble: 16 x 3
# Groups:   species_name [16]
      lat    lon species_name            
    <dbl>  <dbl> <chr>                   
 1  48.8  -124.  Balanophyllia elegans   
 2  59.0    11.0 Caryophyllia smithii    
 3   1.54  125.  Coscinaraea wellsi      
 4  47.8   -59.8 Flabellum alabastrum    
 5 -17.5  -150.  Phymastrea curta        
 6   6.06  100.  Physogyra lichtensteini 
 7   5.77  103.  Plerogyra sinuosa       
 8 -17.6  -150.  Pocillopora woodjonesi  
 9   4.77   73.1 Psammocora contigua     
10   3.8    72.8 Psammocora digitata     
11   1.93 -158.  Psammocora explanulata  
12   4.77   73.1 Psammocora nierstraszi  
13  14.0    48.2 Pseudosiderastrea tayami
14  22.2    39.0 Stylophora pistillata   
15 -17.5  -150.  Tubastraea sp. BMOO04410
16 -17.6  -150.  Verrillofungia concinna 

我想重新排序种名,以便它遵循种名的另一个数据框顺序。

    GeoTree.Scler$tip.label
1    Pocillopora_woodjonesi
2     Stylophora_pistillata
3      Caryophyllia_smithii
4     Balanophyllia_elegans
5  Tubastraea_sp._BMOO04410
6      Flabellum_alabastrum
7   Physogyra_lichtensteini
8         Plerogyra_sinuosa
9          Phymastrea_curta
10       Coscinaraea_wellsi
11   Psammocora_explanulata
12  Verrillofungia_concinna
13      Psammocora_contigua
14      Psammocora_digitata
15 Pseudosiderastrea_tayami
16   Psammocora_nierstraszi

我尝试搜索如何执行此操作,但似乎找不到任何答案。所需输出的一个示例是:

 # A tibble: 16 x 3
    # Groups:   species_name [16]
          lat    lon species_name  
     1 -17.6  -150.  Pocillopora woodjonesi
     2  22.2    39.0 Stylophora pistillata   

第一个数据帧以第二个顺序重新排序。

1 个答案:

答案 0 :(得分:0)

因此,如果您要排序因子并按因子排序:

library(dplyr)
df_1 <- tibble(lat = c(22.2, -17.6),
           lon = c(39.0, -150),
           species_name = c("Stylophora pistillata", "Pocillopora woodjonesi"))



df_2 <- tibble(tip.label = c("Pocillopora_woodjonesi", "Stylophora_pistillata"))

df_1 <- df_1 %>%
  mutate(species_name = gsub(" ", "_", species_name ))

levels <-  df_2$tip.label

df_1 <- df_1 %>%
    mutate(df_1, species_name = factor(species_name, levels = levels))%>%
    arrange(species_name)

    # A tibble: 2 x 3
     lat   lon species_name          
   <dbl> <dbl> <fct>                 
1 -17.6  -150 Pocillopora woodjonesi
2  22.2    39 Stylophora pistillata