Dplyr or Magrittr - tolower?

蓝咒 提交于 2019-12-03 05:02:28

Using magrittr's "compound assignment pipe-operator" %<>% might be, if I understand your question correctly, an even more succinct option.

library("magrittr")
names(iris) %<>% tolower

?`%<>%` # for more

dplyr now allows this:

mydata %>% rename_all(tolower)
iris %>% setNames(tolower(names(.))) %>% head

Or equivalently use replacement function in non-replacement form:

iris %>% `names<-`(tolower(names(.))) %>% head
iris %>% `colnames<-`(tolower(names(.))) %>% head  # if you really want to use `colnames<-`
mtcars %>% 
set_colnames(value = casefold(colnames(.), upper = FALSE)) %>% 
head

casefold is available in base R and can convert in both direction, i.e. can convert to either all upper case or all lower case by using the flag upper, as need might be.

Also colnames() will use only column headers for case conversion.

You could also define a function:

upcase <- function(df) {
  names(df) <- toupper(names(df))
  df
}

library(dplyr)

mtcars %>% upcase %>% select(MPG)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!