使用r

问题描述 投票:0回答:2
starwars %>% mutate (new_column = "Other", .before = 1) # A tibble: 87 × 16 name height mass hair_color skin_color eye_color birth_year sex gender homeworld species films vehicles starships ICP_type .before <chr> <int> <dbl> <chr> <chr> <chr> <dbl> <chr> <chr> <chr> <chr> <list> <list> <list> <chr> <dbl> 1 Luke Skywalker 172 77 blond fair blue 19 male masculine Tatooine Human <chr [5]> <chr [2]> <chr [2]> Other 1 2 C-3PO 167 75 NA gold yellow 112 none masculine Tatooine Droid <chr [6]> <chr [0]> <chr [0]> Other 1 3 R2-D2 96 32 NA white, blue red 33 none masculine Naboo Droid <chr [7]> <chr [0]> <chr [0]> Other 1

它创建了一个“ .before”列,而不是在第一列之前添加新列。
i我尝试了add_column(),它可以正常运行。但是我仍然想知道为什么会出错。谢谢!

您可以尝试使用突变,然后重新安置以指定位置:

r dplyr mutate
2个回答
4
投票

dplyr中的每个完整功能请求:
https://github.com/tidyverse/dplyr/issues/2047

0
投票

.before.after

都应该工作。 toblowing是我的R实例中的结果,该版本在此处发布时在4.4.0处为4.4.0:

> dplyr::starwars |> dplyr::mutate(new_column =  "Other", .before = 1)
# A tibble: 87 × 15
   new_column name        height  mass hair_color skin_color eye_color birth_year sex   gender homeworld species films vehicles
   <chr>      <chr>        <int> <dbl> <chr>      <chr>      <chr>          <dbl> <chr> <chr>  <chr>     <chr>   <lis> <list>  
 1 Other      Luke Skywa…    172    77 blond      fair       blue            19   male  mascu… Tatooine  Human   <chr> <chr>   
 2 Other      C-3PO          167    75 NA         gold       yellow         112   none  mascu… Tatooine  Droid   <chr> <chr>   
 3 Other      R2-D2           96    32 NA         white, bl… red             33   none  mascu… Naboo     Droid   <chr> <chr>   
 4 Other      Darth Vader    202   136 none       white      yellow          41.9 male  mascu… Tatooine  Human   <chr> <chr>   
 5 Other      Leia Organa    150    49 brown      light      brown           19   fema… femin… Alderaan  Human   <chr> <chr>   
 6 Other      Owen Lars      178   120 brown, gr… light      blue            52   male  mascu… Tatooine  Human   <chr> <chr>   
 7 Other      Beru White…    165    75 brown      light      blue            47   fema… femin… Tatooine  Human   <chr> <chr>   
 8 Other      R5-D4           97    32 NA         white, red red             NA   none  mascu… Tatooine  Droid   <chr> <chr>   
 9 Other      Biggs Dark…    183    84 black      light      brown           24   male  mascu… Tatooine  Human   <chr> <chr>   
10 Other      Obi-Wan Ke…    182    77 auburn, w… fair       blue-gray       57   male  mascu… Stewjon   Human   <chr> <chr>   
# ℹ 77 more rows
# ℹ 1 more variable: starships <list>
# ℹ Use `print(n = ...)` to see more rows
	

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.