如何在函数中使用 Dplyr::Rename_At 和 "Starts_with"

How to Use Dplyr::Rename_At Together with "Starts_with" in a Function

library(tidyverse)

使用下面的示例数据,我有两个数据帧 - Df1 和 Df2。我正在尝试创建一个简单的函数,它按字符串选择列 - 在这种情况下,两个数据框中以 "Person" 开头的列以及包含 "Phone" 的所有列。

接下来,我想将两个数据框中的 "Person" 列重命名为 "Id"。

但是,我无法使重命名功能正常工作。

这是第一次尝试...

Funs<-function(Df){
Df%>%select(starts_with("Person"),contains("Phone"))%>%
rename_at(vars(starts_with("Person"),"Id"))
}

下面是我试过的 "rename" 的一些其他变体,但没有用...

rename_at(vars(starts_with("Person"),funs("Id"=.)))

rename("Id"=names(.)[1])

我该如何纠正?我试图在这个网站上找到类似的问题,因为它看起来很简单,但我找不到任何有用的东西...

示例数据:

`Person #`<-c(199,148,148,145,177,165,144,121,188,188,188,111)
`Phone #1`<-c(6532881717,6572231223,6541132112,6457886543,6548887777,7372222222,6451123425,6783450101,7890986543,6785554444,8764443344,6453348736)
`Phone #2`<-c(NA,NA,NA,NA,NA,7372222222,NA,NA,NA,6785554444,NA,NA)
Animals<-c("Cat","Dog","Elephant","Giraffe","Bird","Snake","Skunk","Raccoon","Moose","Turtle","Beaver","Porcupine")

Df1<-data.frame(`Person #`,`Phone #1`,`Phone #2`, Animals)


`Person ID #`<-c(199,148,142,145,177,165,144,121,182,109,188,111)
`Phone s 1`<-c(6532881717,6572231223,6541132112,6457886543,6548887777,7372222222,6451123425,6783450101,7890986543,6785554400,8764443344,6453348736)
`Phone s 2`<-c(NA,NA,NA,NA,NA,7372222222,NA,NA,NA,6785554444,NA,NA)
Animals<-c("Cat","Dog","Elephant","Giraffe","Bird","Snake","Skunk","Raccoon","Moose","Turtle","Beaver","Porcupine")

Df2<-data.frame(`Person ID #`,`Phone s 1`,`Phone s 2`, Animals)

这两个选项都有效,但以这种方式重命名似乎很脆弱;仅当您只有一列满足条件时才有效,即 starts_with('Person') :

Df1 %>% rename_at(vars(starts_with('Person')), ~ 'ID')

Df1 %>% rename_at(1, ~ 'ID')

两者都给出:

#    ID   Phone..1   Phone..2   Animals
#1  199 6532881717         NA       Cat
#2  148 6572231223         NA       Dog
#3  148 6541132112         NA  Elephant
#  ...

或使用funs:

Df1 %>% rename_at(vars(starts_with("Person")),funs(function(.) 'ID'))

以上对我不起作用。这个例子做 运行:

tribble(
  ~col_name_1, ~col_name_2_foo, ~col_name_3_foo,
  "a", 1, 3,
  "b", 2, 2,
  "c", 3, 1
) %>%
rename_at(
  vars(ends_with("_foo")), function(x) { toupper(x) }
)

# A tibble: 3 x 3
  col_name_1 COL_NAME_2_FOO COL_NAME_3_FOO
  <chr>               <dbl>          <dbl>
1 a                       1              3
2 b                       2              2
3 c                       3              1

rename_at(vars(ends_with("_foo")), toupper) 如果您要使用的函数已经定义,也可以使用。