2015-07-22 64 views
2

需要創建一個選項組,供Shiny中的selectizeInput小部件使用。簡單的數據幀到R中的複雜列表轉換

開始樣品數據幀

df <- data.frame("Region" = c("Eastern", "Eastern", "Western", "Western"), 
       "City" = c("New york", "New Jersey", "California", "Washington"), 
       "Abb" = c("NY", "NJ", "CA", "WA")) 

通緝名單

l <- list(Eastern = c(`New York` = 'NY', `New Jersey` = 'NJ'), 
    Western = c(`California` = 'CA', `Washington` = 'WA')) 

手冊解決方案

Eastern <- df[which(df$Region == "Eastern"),] 
Western <- df[which(df$Region == "Western"),] 
list(Eastern = setNames(Eastern$Abb, Eastern$City), Western = setNames(Western$Abb, Western$City)) 

有沒有更好的辦法做到這一點

回答

4

您可以試試split

with(df, split(setNames(as.character(Abb), City), Region)) 
#$Eastern 
# New york New Jersey 
#  "NY"  "NJ" 

#$Western 
# California Washington 
#  "CA"  "WA"