简体   繁体   English

Dplyr或Magrittr - tolower?

[英]Dplyr or Magrittr - tolower?

Is it possible to set all column names to upper or lower within a dplyr or magrittr chain? 是否可以在dplyr或magrittr链中将所有列名设置为高位或低位?

In the example below I load the data and then, using a magrittr pipe, chain it through to my dplyr mutations. 在下面的示例中,我加载数据,然后使用magrittr管道将其链接到我的dplyr突变。 In the 4th line I use the tolower function , but this is for a different purpose: to create a new variable with lowercase observations. 在第4行中我使用了tolower函数,但这是出于不同的目的:使用小写观察创建一个新变量。

mydata <- read.csv('myfile.csv') %>%
    mutate(Year = mdy_hms(DATE),
           Reference = (REFNUM),
           Event = tolower(EVENT)

I'm obviously looking for something like colnames = tolower but know this doesn't work/exist. 我显然正在寻找像colnames = tolower这样的东西,但知道这不起作用/存在。

I note the dplyr rename function but this isn't really helpful. 我注意到了dplyr rename功能,但这并没有多大帮助。

In magrittr the colname options are: 在magrittr中,colname选项是:

set_colnames instead of base R's colnames<- set_colnames而不是base R的colnames<-
set_names instead of base R's names<- set_names而不是base R的names<-

I've tried numerous permutations with these but no dice. 我尝试了很多这些但没有骰子的排列。

Obviously this is very simple in base r. 显然,这在基础r中非常简单。

names(mydata) <- tolower(names(mydata))

However it seems incongruous with the / philosophies that you'd have to do that as a clunky one liner, before moving on to an elegant chain of dplyr/magrittr code. 然而,在进入优雅的dplyr / magrittr代码链之前,与 / 哲学似乎不 ,你必须做一个笨重的单行班。

dplyr现在允许这样:

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<-`

Using magrittr 's "compound assignment pipe-operator" %<>% might be, if I understand your question correctly, an even more succinct option. 如果我理解你的问题,使用magrittr的“复合赋值管道运算符” %<>%可能是一个更简洁的选项。

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

?`%<>%` # for more
mtcars %>% 
set_colnames(value = casefold(colnames(.), upper = FALSE)) %>% 
head

casefold is available in base R and can convert in both direction, ie can convert to either all upper case or all lower case by using the flag upper , as need might be. casefold在base R中可用,并且可以在两个方向上进行转换,即可以根据需要使用flag upper转换为全大写或全小写。

Also colnames() will use only column headers for case conversion. 此外, colnames()将仅使用列标题进行大小写转换。

You could also define a function: 您还可以定义一个函数:

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

library(dplyr)

mtcars %>% upcase %>% select(MPG)

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

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