简单的数据帧到R中的复杂列表转换

时间:2015-07-22 06:06:06

标签: r

需要创建一个选项组,供Shiny中的selectizeInput小部件使用。

启动示例数据框

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))

有更好的方法吗

1 个答案:

答案 0 :(得分:4)

您可以尝试split

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

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