Home > Net >  why passing names(.) to forumla in rename_with doesn't work?
why passing names(.) to forumla in rename_with doesn't work?

Time:12-30

Not sure why the first one has an error but the second line works? My understanding was using names(.) in the formulas tells R to use the data before pipe operator. It seems to work for .cols argument but not for formula.

iris%>%rename_with(~gsub("Petal","_",names(.)),all_of(names(.)))
iris%>%rename_with(~~gsub("Petal","_",names(iris)),all_of(names(.)))

CodePudding user response:

rename_with applies a function to the names of the passed data frame. The function should be one that, given the vector of names, returns the altered names, so the syntax is much simpler than you are trying to make it:

iris %>%
  rename_with(~ gsub("Petal", "_", .x))
#>   Sepal.Length Sepal.Width _.Length _.Width Species
#> 1          5.1         3.5      1.4     0.2  setosa
#> 2          4.9         3.0      1.4     0.2  setosa
#> 3          4.7         3.2      1.3     0.2  setosa
#> 4          4.6         3.1      1.5     0.2  setosa
#> 5          5.0         3.6      1.4     0.2  setosa
#> 6          5.4         3.9      1.7     0.4  setosa
#... etc
  • Related