2017-09-25 96 views
1

我想從df1產生一個類似於df3的數據框,即爲無變量的變量添加一個前綴(important_),同時不會觸及具有某些前綴(gea_,win_,hea_)的變量。到目前爲止,我只管理類似df2的東西,其中important_變量在單獨的數據框中結束,但我希望所有變量都在同一個數據框中。任何想法都會非常感激。向某些變量添加前綴而不觸及其他變量?

我有什麼:

library(dplyr) 

df1 <- data.frame("hea_income"=c(45000,23465,89522),"gea_property"=c(1,1,2) ,"win_state"=c("AB","CA","GA"), "education"=c(1,2,3), "commute"=c(13,32,1)) 

df2 <- df1 %>% select(-contains("gea_")) %>% select(-contains("win_")) %>% select(-contains("hea_")) %>% setNames(paste0('important_', names(.))) 

我想什麼:

df3 <- data.frame("hea_income"=c(45000,23465,89522),"gea_property"=c(1,1,2) ,"win_state"=c("AB","CA","GA"), "important_education"=c(1,2,3), "important_commute"=c(13,32,1)) 

回答

1

的選擇是rename_at

dfN <- df1 %>% 
     rename_at(4:5, funs(paste0("important_", .))) 
identical(dfN, df3) 
#[1] TRUE 

我們也可以包括一些正則表達式,如果我們想通過數字索引來指定變量。這裏的假設是,所有這些列不已經有一個_

df1 %>% 
    rename_at(vars(matches("^[^_]*$")), funs(paste0("important_", .))) 
# hea_income gea_property win_state important_education important_commute 
#1  45000   1  AB     1    13 
#2  23465   1  CA     2    32 
#3  89522   2  GA     3     1 

或用matches-

df1 %>% 
    rename_at(vars(-matches("_")), funs(paste0("important_", .))) 
# hea_income gea_property win_state important_education important_commute 
#1  45000   1  AB     1    13 
#2  23465   1  CA     2    32 
#3  89522   2  GA     3     1 

所有上述三個方案得到預期的輸出作爲OP的帖子

顯示
0

這裏的另一種可能性:

names(df1) <- names(df1) %>% {ifelse(grepl("_",.),.,paste0("important_",.))} 
# > df1 
# hea_income gea_property win_state important_education important_commute 
# 1  45000   1  AB     1    13 
# 2  23465   1  CA     2    32 
# 3  89522   2  GA     3     1 
+0

對我一直sl,,我可以用'name(df1)%>%inset(!grepl(「_」,。),paste0(「important _」,。)[which(!grepl(「_」 ,))])''但它不再那麼漂亮了,所以我從回答中刪除了它 –

+0

(即使沒有不必要的'哪個') –

+0

相關:https://stackoverflow.com/questions/46409397/assigning-to -temp-變量 - 內 - 的-maggritr命令鏈 –

相關問題