![](/img/trans.png)
[英]dplyr 0.8.0 mutate_at: use of custom function without overwriting original columns
[英]mutate_at() to rename multiple variables without altering original columns
我想使用 mutate_at() 一次改變幾個變量。 到目前為止,這就是我一直在做的事情,但是由於我正在處理一長串要重新編碼/重命名的變量,所以我想知道如何使用 mutate_at() 來做到這一點。 我想保留原始列,這就是為什么我不使用 rename() 而是使用 mutate() 的原因。 這是我通常做的:
df <- df %>%
mutate(q_50_a = as.numeric(`question_50_part_a: very long very long very long very long` == "yes"),
q_50_b = as.numeric(`question_50_part_b: very long very long very long very long` == "yes"),
q_50_c = as.numeric(`question_50_part_c: very long very long very long very long` == "yes"))
這是我到目前為止所擁有的:
df <- df %>% mutate_at(vars(starts_with("question_50")), funs(q_50 = as.numeric(. == "yes")))
它可以工作並創建一個新的數字變量,但我不確定如何讓它重命名新變量,如下所示:q_50_a、q_50_b、q_50_c 等。
謝謝你。
編輯:這就是數據的樣子(除了有更多的列看起來都一樣)
question_50_part_a: a very long title question_50_part_b: a very long title
yes yes
yes no
yes no
yes yes
no no
yes yes
但想要這樣:
q_50_a q_50_b
1 1
1 0
1 0
1 1
0 0
1 1
但我想保持原來的列不變,並用較短的名稱和數字二進制編碼簡單地改變這些新列。
我們可以使用rename_at
重命名新列。
library(dplyr)
df %>%
mutate_at(vars(starts_with('question_50')),
list(new = ~as.numeric(. == 'yes'))) %>%
rename_at(vars(ends_with('new')),
~sub('\\w+(_\\d+)_part(\\w+):.*', 'q\\1\\2', .))
# question_50_part_a: a very long title question_50_part_b: a very long title
#1 yes yes
#2 yes no
#3 yes no
#4 yes yes
#5 no no
#6 yes yes
# q_50_a q_50_b
#1 1 1
#2 1 0
#3 1 0
#4 1 1
#5 0 0
#6 1 1
這是一種遍歷每一列的方法:
column_names = colnames(df)
# optional filter out column names you don't want to change here
for(col in column_names){
# construct replacement name
col_replace = paste0("q_", substr(col, 10, 11), "_", substr(col, 18, 18))
# assign and drop old column
df = df %>%
mutate(!!sym(col_replace) := ifelse(!!sym(col) == "yes", 1, 0)) %>%
select(-!!sym(col))
}
注意事項:
!!sym(col)
構造獲取存儲在col
中的文本字符串並將其轉換為列名。:=
而不是=
因為 LHS 需要在分配發生之前進行一些評估。ifelse
而不是as.numeric
但您可以隨意編碼等號的 RHS。col_replace
輸入名稱的格式做出一些假設。 如果一切都是相同的長度,這應該可以。 如果字符數不同(例如 Q_9_a 和 Q_10_a),那么您可能希望使用基於strsplit
的方法。-
符號使其排除指定列
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.