[英]Rename all columns of dataframe in dplyr without using rename()
我想以一種整潔的方式重命名我的變量,但我不喜歡重命名選項。 通常我會用這個:
df <- structure(list(hv001 = c(1L, 1L, 1L, 1L,
1L, 1L), hv002 = 1:6, hv003 = c(2L, 1L, 1L, 3L, 1L, 1L), hv008 = c(1386L,
1386L, 1386L, 1386L, 1386L, 1386L), hv009 = c(6L, 7L, 3L, 7L,
4L, 6L), hv025 = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("rural",
"urban"), class = "factor"), hv106_01 = structure(c(3L, 3L, 5L,
NA, 5L, 3L), .Label = c("don't know", "higher", "no education, preschool",
"primary", "secondary"), class = "factor"), hv115_01 = structure(c(2L,
2L, 2L, 2L, 2L, 2L), .Label = c("divorced", "married", "never married",
"widowed"), class = "factor"), ha1_01 = c(NA, NA, 22L, 42L, 25L,
37L), ha2_01 = c(NA, NA, 494L, 501L, 557L, 800L), ha3_01 = c(NA,
NA, 1555L, 1498L, 1562L, 1536L), ha53_01 = c(NA, NA, 111L, 144L,
127L, 131L), ha54_01 = structure(c(NA, NA, 2L, 1L, 1L, 1L), .Label = c("no/don't know",
"yes"), class = "factor"), ha57_01 = structure(c(NA, NA, 3L,
3L, 3L, 3L), .Label = c("mild", "moderate", "not anemic", "severe"
), class = "factor")), row.names = c(NA, 6L), class = "data.frame")
colnames(df) <- c("cluster", "household_number", "respondent_line_number", "date", "num_household_members", location", "education", "marital_status", "age", "weight", "height",
"hemoglobin", "pregnancy_status", "anemia")
我知道我可以這樣做:
df <- df %>% rename(cluster = hv001, household_number = hv002, etc)
但實際上必須輸入舊的變量名,這樣更不整潔/效率較低。 有沒有辦法結合舊方法或者是否有更有效的方法來重命名所有列?
謝謝!
無需逐列重命名。 您可以使用 set_names,它等同於 setNames。 然后是
df <- df %>%
set_names(nm = c("cluster", "household_number", "respondent_line_number", "date", "num_household_members", location", "education", "marital_status", "age", "weight", "height",
"hemoglobin", "pregnancy_status", "anemia"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.