在循环中使用prop.table时,从列表中引用变量名称

时间:2018-06-04 19:27:35

标签: r

我正在尝试使用R中的const numDataPoints = [ { x0: {x: 807, y: 625}, x1: {x: 15, y: 20}, x2: {x: 5, y: 20} }, { x0: {x: 11, y: 6}, x1: {x: 16, y: 21}, x2: {x: 7, y: 22} } ]; // Object.values, same structure console.log(numDataPoints.map((obj) => Object.values(obj).map(({x, y}) => [x, y]))); // Object.values, flattened with concat console.log([].concat(...numDataPoints.map((obj) => Object.values(obj).map(({x, y}) => [x, y])))); // Object.values, flattened with flatMap console.log(numDataPoints.flatMap((obj) => Object.values(obj).map(({x, y}) => [x, y]))); // Destructuring, same structure console.log(numDataPoints.map(({x0, x1, x2}) => [x0, x1, x2].map(({x, y}) => [x, y]))); // Destructuring, flattened with concat console.log([].concat(...numDataPoints.map(({x0, x1, x2}) => [x0, x1, x2].map(({x, y}) => [x, y])))); // Destructuring, flattened with flatMap console.log(numDataPoints.flatMap(({x0, x1, x2}) => [x0, x1, x2].map(({x, y}) => [x, y])));循环从列联表中快速生成多个ggplot2图。每个变量(for)都由一个变量({{1} })。

我编写了以下循环,但不断收到错误。

R1...R7

我尝试在segment_r中加入question_names<-paste("R",1:7,sep='') # Create list with question names attach(df) for (i in length(question_names)) { question_names[i]<-factor(question_names[i]) means<-prop.table(table(get(question_names[i]),segment_r),2)*100 means.long<-melt(means,id.vars="segment_r") p<-ggplot(means.long,aes(x=Var1,y=value,fill=factor(Var2)))+ geom_bar(stat="identity",position="dodge")+coord_flip()+ scale_fill_discrete(name="Segment", breaks=c(1:4), labels=c(1:4))+ xlab("")+ylab("Mean Percentage") p <- p + facet_wrap( ~ Var2, ncol=4) p } detach(df) ,这会产生错误:get)。但是,省略table也不起作用:Error in get(question_names[i]) : object '1' not found

思考?我也对一个生成多个图形而不使用get的解决方案持开放态度 - 在这里提高速度。

根据请求,下面的示例数据:

Error in table(question_names[i], segment_r) : all arguments must have the same length

1 个答案:

答案 0 :(得分:1)

我不清楚你想用这些情节“做”到底是什么。但是将代码翻译成“有效”的东西可能看起来像这样

library(reshape2)
library(ggplot2)

question_names <- paste("R", 1:7, sep='') # Create list with question names

for (q in question_names) {
  means <- prop.table(table(df[[q]], df[["segment_r"]]),2)*100
  means.long <- melt(means, id.vars="segment_r")
  p <- ggplot(means.long, aes(x=Var1, y=value, fill=factor(Var2)))+
    geom_bar(stat="identity",position="dodge") + coord_flip()+
    scale_fill_discrete(name="Segment",
                        breaks=c(1:4),
                        labels=c(1:4))+
    xlab("")+ylab("Mean Percentage")
  p <- p + facet_wrap( ~ Var2, ncol=4)
  print(p)
}

这会将所有绘图放到图形窗口中(尽管最后一个绘图会覆盖上一个绘图)。但这至少摆脱了attach()get()