简体   繁体   English

Dplyr 在指定位置改变新列

[英]Dplyr mutate new column at a specified location

An example:一个例子:

a = c(10,20,30)
b = c(1,2,3)
c = c(4,5,6)
d = c(7,8,9)
df=data.frame(a,b,c,d)

library(dplyr)

df_1 = df %>% mutate(a1=sum(a+1))

How do I add "a1" after "a" (or any other defined position) and NOT at the end?如何在“a”(或任何其他定义的位置)之后而不是在最后添加“a1”?

Thank you.谢谢你。

An update that might be useful for others who find this question - this can now be achieved directly within mutate (I'm using dplyr v1.0.2).可能对发现此问题的其他人有用的更新 - 现在可以直接在mutate实现(我使用的是dplyr v1.0.2)。

Just specify which existing column the new column should be positioned after or before, eg:只需指定新列应位于哪个现有列之后或之前,例如:

df_after <- df %>% 
   mutate(a1=sum(a+1), .after = a)

df_before <- df %>% 
   mutate(a1=sum(a+1), .before = b)

Another option is add_column from tibble另一种选择是add_columntibble

library(tibble)    
add_column(df, a1 = sum(a + 1), .after = "a")
#   a a1 b c d
#1 10 63 1 4 7
#2 20 63 2 5 8
#3 30 63 3 6 9

Extending on www's answer, we can use dplyr's select_helper functions to reorder newly created columns as we see fit:扩展 www 的答案,我们可以使用 dplyr 的select_helper函数来重新排序我们认为合适的新创建的列:

library(dplyr)

## add a1 after a
df %>% 
    mutate(a1 = sum(a + 1)) %>%
    select(a, a1, everything())
#>    a a1 b c d
#> 1 10 63 1 4 7
#> 2 20 63 2 5 8
#> 3 30 63 3 6 9

## add a1 after c
df %>% 
    mutate(a1 = sum(a + 1)) %>%
    select(1:c, a1, everything())
#>    a b c a1 d
#> 1 10 1 4 63 7
#> 2 20 2 5 63 8
#> 3 30 3 6 63 9

The mutate function will always add the newly created column at the end. mutate函数将始终在末尾添加新创建的列。 However, we can sort the column alphabetically after the mutate function using select .但是,我们可以使用selectmutate函数之后按字母顺序对列进行排序。

library(dplyr)

df_1 <- df %>% 
  mutate(a1 = sum(a + 1)) %>%
  select(sort(names(.)))
df_1
#    a a1 b c d
# 1 10 63 1 4 7
# 2 20 63 2 5 8
# 3 30 63 3 6 9

dplyr >= 1.0.0 dplyr >= 1.0.0

relocate was added as a new verb to change the order of one or more columns. relocate被添加为一个新动词以更改一列或多列的顺序。 If you pipe the output of your mutate the syntax for relocate also uses .before and .after arguments:如果你管的输出mutate的语法relocate也使用.before.after参数:

df_1 %>% 
  relocate(a1, .after = a)
   a a1 b c d
1 10 63 1 4 7
2 20 63 2 5 8
3 30 63 3 6 9

An additional benefit is you can also move multiple columns using any tidyselect syntax:另一个好处是您还可以使用任何tidyselect语法移动多个列:

df_1 %>% 
  relocate(c:a1, .before = b)
   a c d a1 b
1 10 4 7 63 1
2 20 5 8 63 2
3 30 6 9 63 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM