![](/img/trans.png)
[英]dplyr: apply sequential functions to variables without creating new variables in a single mutate(across(...))
[英]Creating new variables with dplyr::mutate() without conflicting names
我正在編寫一系列在內部使用dplyr
來操作數據的函數。
在使用數據集時,我想在很多地方向數據集添加新變量。 但是,我不確定如何命名這些新變量以避免覆蓋數據中已有的變量,因為我不知道傳遞的數據集中有什么。
在基礎 RI 中可以這樣做:
df <- data.frame(a = 1:5)
df[, ncol(df)+1] <- 6:10
它將為新添加的變量選擇一個不與任何現有名稱沖突的名稱。 我想這樣做是dplyr
而不是分手的一致應用dplyr
回到基地-R。
到目前為止,我想到的所有解決方案都感覺非常笨拙,或者無論如何都需要使用一堆 base-R futzing,這並不比僅在 base-R 中添加變量好:
names()
向量並使用多種方法之一生成不在向量中的名稱 在dplyr
是否有一種直接的方法可以做到這dplyr
? 讓它在mutate
工作將是理想的,盡管我認為bind_cols
或tibble::add_column
也可以。
我嘗試過的一些方法不起作用:
df <- data.frame(a = 1:5)
# Gives the new variable a fixed title which might already be in there
df %>% mutate(6:10)
df %>% tibble::add_column(6:10)
df %>% mutate(NULL = 6:10)
# Error
df %>% bind_cols(6:10)
df %>% mutate( = 6:10)
df %>% mutate(!!NULL := 6:10)
# And an example of the kind of function I'm looking at:
# This function returns the original data arranged in a random order
# and also the random variable used to arrange it
arrange_random <- function(df) {
df <- df %>%
mutate(randomorder = runif(n())) %>%
arrange(randomorder)
return(df)
}
# No naming conflict, no problem!
data <- data.frame(a = 1:5)
arrange_random(data)
# Uh-oh, the original data gets lost!
data <- data.frame(randomorder = 1:5)
arrange_random(data)
我現在發布這個解決方案。 這聽起來像是一個不太了解自己數據的情況,所以我認為一個好方法是在函數中包含一個if-else
語句。 邏輯是用戶選擇一些任意的新名稱作為其原始變量名稱的后綴,但如果新名稱已包含在原始數據中,則該函數將返回錯誤。 否則,該函數運行並返回原始數據和新變異的數據。
df <- data.frame(a = 1:5, b=11:15, c=21:25)
# define function with if-else statement to catch any possible duplicates
addnew <- function(data,name='newvar'){
if(sum(grepl(name,names(data),ignore.case=T))>0)
{stop('Error! Possible duplicate names with your new variable names')} else{
data1 <- data %>% mutate_all(list( ~ runif(n())))
names(data1) <- paste0(names(data1),'_',name)
bind_cols(data,data1)
}
}
addnew(df,'new')
a b c a_new b_new c_new
1 1 11 21 0.2875775 0.0455565 0.9568333
2 2 12 22 0.7883051 0.5281055 0.4533342
3 3 13 23 0.4089769 0.8924190 0.6775706
4 4 14 24 0.8830174 0.5514350 0.5726334
5 5 15 25 0.9404673 0.4566147 0.1029247
# try with new data that should throw an error
df <- data.frame(a_new = 1:5,b=11:15,c=21:25)
addnew(df,'new')
Error in addnew(df, "new") :
Error! Possible duplicate names with your new variable names
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.