gpt4 book ai didi

r - 用 dplyr 大写

转载 作者:行者123 更新时间:2023-12-04 15:17:36 27 4
gpt4 key购买 nike

我正在使用 dplyr 进行数据清理。
我想做的一件事是将某些列中的值大写。

    data$surname
john
Mary
John
mary
...

我想我必须使用 变异 dplyr 的功能与这样的东西
    titleCase <- function(x) {
+ s <- strsplit(as.character(x), " ")[[1]]
+ paste(toupper(substring(s, 1, 1)), substring(s, 2),
+ sep = "", collapse = " ")
+ }

但是如何将两者结合起来呢?我收到各种错误或截断的数据帧

谢谢

最佳答案

我们可以使用 sub

sub("(.)", "\\U\\1", data$surname, perl=TRUE)
#[1] "John" "Mary" "John" "Mary"

dplyr 中实现工作流程
library(dplyr)
data %>%
mutate(surname = sub("(.)", "\\U\\1", surname, perl=TRUE))

如果我们需要在多个列上执行此操作
data %>%
mutate_each(funs(sub("(.)", "\\U\\1", ., perl=TRUE)))

只是为了检查
res <- data1 %>%  
mutate(surname = sub("(.)", "\\U\\1", surname, perl=TRUE))
sum(grepl("[A-Z]", substr(res$surname, 1,1)))
#[1] 500000

数据
data <- data.frame(surname=c("john", "Mary", "John", "mary"), 
firstname = c("abe", "Jacob", "george", "jen"), stringsAsFactors=FALSE)

data1 <- data.frame(surname = sample(c("john", "Mary", "John", "mary"),
500000, replace=TRUE), stringsAsFactors=FALSE)

关于r - 用 dplyr 大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37158678/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com