dplyr pipes - 如何更改原始数据帧

dplyr pipes - How to change the original dataframe

当我不使用管道时,我可以使用此命令更改原始daframe

df<-slice(df,-c(1:3))%>% # delete top 3 rows
df<-select(df,-c(Col1,Col50,Col51)) # delete specific columns

如何用一根管子做到这一点?我试过了,但是 sliceselect 函数不会更改原始数据框。

df%>%
  slice(-c(1:3))%>% 
  select(-c(Col1,Col50,Col51))

我想改掉原来的df

您绝对可以使用 df <- df %>% ...df %>% ... -> df 等成语来完成作业。但是您也可以通过在管道的开头使用 magrittr 复合赋值运算符 %<>% 来避免冗余(即声明 df 两次)。

来自 magrittr 小插图:

The compound assignment pipe operator %<>% can be used as the first pipe in a chain. The effect will be that the result of the pipeline is assigned to the left-hand side object, rather than returning the result as usual.

所以用你的代码,我们可以做到

library(magrittr)  ## came with your dplyr install
df %<>% slice(-(1:3)) %>% select(-c(Col1, Col50, Col51))

这会将 df 传送到表达式中并更新 df 作为结果。

更新: 在评论中,您注意到设置列名称的问题。幸运的是 magrittr 提供了在管道中设置属性的函数。请尝试以下操作。

df %<>% 
    set_colnames(sprintf("Col%d", 1:ncol(.))) %>% 
    slice(-(1:3)) %>%
    select(-c(Col1,Col50,Col51))

请注意,由于我们有一个数据框,我们还可以使用 setNames() (stats) 或 set_names() (magrittr) 代替 set_colnames()


感谢 Steven Beaupre 添加小插图中的注释。