在R中创建了一个嵌套的命名列表

时间:2018-06-07 22:24:17

标签: r

假设我有一个这样的列表:

df = list(
Happy = c('Yes','No','Maybe'),
Satisfaction = c('Strongly Agree','Agree','Disagree','Strongly Disagree')
)

但我需要什么

df = list(
    Happy = c('Yes'='Happy-yes','No'='Happy-yes','Maybe'='Happy-maybe'),
    Satisfaction = c('Strongly Agree'='Satisfaction-Strongly Agree",'Agree'="Satisfaction-Agree",'Disagree'='Satisfaction-Disagree','Strongly Disagree'='Satisfaction-Strongly Disagree'))

然后我会将此列表传递给Shiny中的choices()输入,但这样我就可以将响应映射回命名列表的分组。

2 个答案:

答案 0 :(得分:3)

MappastesetNames用旧值标记新值:

Map(function(nm,x) setNames(paste(nm,x,sep="-"),x), names(df), df)
#$Happy
#          Yes            No         Maybe 
#  "Happy-Yes"    "Happy-No" "Happy-Maybe" 
# 
#$Satisfaction
#                  Strongly Agree                            Agree 
#   "Satisfaction-Strongly Agree"             "Satisfaction-Agree" 
#                        Disagree                Strongly Disagree 
#         "Satisfaction-Disagree" "Satisfaction-Strongly Disagree" 

答案 1 :(得分:2)

您可以选择lapply来执行此操作:

dfx <- lapply(1:length(df), function(i)paste0(names(df)[i],"-",df[[i]]))
dfxf <- lapply(1:length(dfx), function(i) `names<-`((dfx[[i]]), df[[i]]))
names(dfxf) <- names(df)

<强>输出

 > dfxf
$Happy
          Yes            No         Maybe 
  "Happy-Yes"    "Happy-No" "Happy-Maybe" 

$Satisfaction
                  Strongly Agree 
   "Satisfaction-Strongly Agree" 
                           Agree 
            "Satisfaction-Agree" 
                        Disagree 
         "Satisfaction-Disagree" 
               Strongly Disagree 
"Satisfaction-Strongly Disagree" 

请注意,OP所需的输出似乎有一点错字,因为你可以看到,而不是“Happy-No”它在第一个列表的第二个元素中说“Happy-Yes”套管也关闭(假设是这种情况)。