【问题标题】:Lowercase all character columns except xyz in dataframe小写数据框中除 xyz 之外的所有字符列
【发布时间】:2022-01-15 14:46:50
【问题描述】:

foo() 将数据框except= 的所有字符列小写,其名称由用户提供。

我想知道为什么当我提供except="study" 时,foo 错误地将study 中的study 列小写在data 中?

可重现的代码和所需的输出如下。

m="
study cap  back
AA    L    1
BB    F    2
CC    H    8"
data <- read.table(text=m,h=T)


foo <- function(X, except = NULL){
  y <- sapply(setdiff(names(X), except), function(x) is.character(as.vector(X[[x]])))
  X[y] <- lapply(X[y], tolower)
return(X)
}
#=== EXAMPLE OF USE:
foo(data, except = c("study"))

Desired_output=
"
study cap  back
AA    l    1
BB    f    2
CC    h    8"

【问题讨论】:

    标签: r dataframe function dplyr character


    【解决方案1】:

    这里有两种方法可以实现这一点-

    基础 R -

    foo <- function(X, except = NULL){
      y <- names(Filter(is.character, X[setdiff(names(X), except)]))
      X[y] <- lapply(X[y], tolower)
      return(X)
    }
    foo(data, except = c("study"))
    
    #  study cap back
    #1    AA   l    1
    #2    BB   f    2
    #3    CC   h    8
    

    使用dplyr -

    library(dplyr)
    
    foo <- function(X, except = NULL){
      X %>%
        mutate(across(where(is.character) & 
                      all_of(setdiff(names(X), except)), tolower))
    }
    
    foo(data, except = c("study"))
    

    【讨论】:

    • 感谢@Ronak Shah 的回答。为什么这对data &lt;- data.frame(Study = c("AA", "BB", "CC"), Cap = c("L", "F", "H"), Back = c(1, 2, 8)); except &lt;- "Study" 不起作用?
    • 如果您使用我的示例 dataexcept 以及您的 foo(),则不会将列转换为小写。你介意自己试试吗?
    • 没关系。对于那个很抱歉。我在想列名而不是值。
    • 您可以简化为across(where(is.character) &amp; !except, tolower)
    • 感兴趣的问题HERE
    猜你喜欢
    • 2013-10-04
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 2016-11-19
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多