【发布时间】:2018-10-25 21:38:03
【问题描述】:
我的代码可以根据客户名称从数据库中提取和处理数据。某些客户端的数据可能不包含特定列名,例如 last_name 或 first_name。对于不使用last_name 或first_name 的客户,我不在乎。对于确实使用其中任何一个字段的客户,我需要使用toupper() mutate() 这些列,以便稍后在 ETL 流程中加入这些标准化字段。
现在,我正在使用一系列 if() 语句和一些辅助函数来查看数据框的名称,然后在它们存在时进行变异。 I'm using if() statements because ifelse() is mostly vectorized and doesn't handle dataframes well.
library(dplyr)
set.seed(256)
b <- data.frame(id = sample(1:100, 5, FALSE),
col_name = sample(1000:9999, 5, FALSE),
another_col = sample(1000:9999, 5, FALSE))
d <- data.frame(id = sample(1:100, 5, FALSE),
col_name = sample(1000:9999, 5, FALSE),
last_name = sample(letters, 5, FALSE))
mutate_first_last <- function(df){
mutate_first_name <- function(df){
df %>%
mutate(first_name = first_name %>% toupper())
}
mutate_last_name <- function(df){
df %>%
mutate(last_name = last_name %>% toupper())
}
n <- c("first_name", "last_name") %in% names(df)
if (n[1] & n[2]) return(df %>% mutate_first_name() %>% mutate_last_name())
if (n[1] & !n[2]) return(df %>% mutate_first_name())
if (!n[1] & n[2]) return(df %>% mutate_last_name())
if (!n[1] & !n[2]) return(df)
}
我得到了我期望得到的东西
> b %>% mutate_first_last()
id col_name another_col
1 48 8318 6207
2 39 7155 7170
3 16 4486 4321
4 55 2521 8024
5 15 1412 4875
> d %>% mutate_first_last()
id col_name last_name
1 64 7438 A
2 43 4551 Q
3 48 7401 K
4 78 3682 Z
5 87 2554 J
但这是处理此类任务的最佳方式吗?动态查看数据框中是否存在列名,如果存在则对其进行变异?在这个函数中必须有多个 if() 语句似乎很奇怪。 是否有更简化的方式来处理这些数据?
【问题讨论】: