带循环的Barplot创建问题

时间:2019-02-21 09:17:09

标签: r bar-chart cycle

我有一个数据集(民意调查的结果),该数据集分为38个区域,我想编写一个循环来为每个特定区域创建一个百分比答案图。

因此,如果我编写以下代码(区域号为“ 6”时将“ i”表示为“ 6”,其中“ psu”是负责区域号的变量),一切正常。

reg <- subset(rlmsq, psu == "6")

    s <- c(sum(reg$employee == "1", na.rm = TRUE)*100/sum(reg$employee !="", na.rm = TRUE),
           sum(reg$employee == "2", na.rm = TRUE)*(100/2)/sum(reg$employee !="", na.rm = TRUE),
           sum(reg$employee_affect == "1", na.rm = TRUE)*100/sum(reg$employee_affect !="", na.rm = TRUE),
           sum(reg$employee_affect == "2", na.rm = TRUE)*(100/2)/sum(reg$employee_affect !="", na.rm = TRUE),
           sum(reg$employee_affect == "3", na.rm = TRUE)*(100/3)/sum(reg$employee_affect !="", na.rm = TRUE),
           sum(reg$employee_affect == "7", na.rm = TRUE)*(100/7)/sum(reg$employee_affect !="", na.rm = TRUE),
           sum(reg$employee_affect == "8", na.rm = TRUE)*(100/8)/sum(reg$employee_affect !="", na.rm = TRUE))

    barplot(s,
            main = "ANSW. #3_1 ",              
            xlab = "Answers subpoints",         
            ylab = "Percetage",              
            ylim = c(0, 100),
            names.arg = c("Yes", "No",
                          "Not-at-all", "Slightly",
                          "Strongly", "DTA",
                          "Refusal"),
            col = "blue",  cex.names = 0.6)

但是,一旦我尝试创建一个循环并将“ i”用作多个区域(下一个),我唯一得到的就是空图,因为没有数据。

par(mar=c(2,2,2,2))
par(mfrow=c(5,8))

for (i in 1:38) {

reg <- subset(rlmsq, psu == "i")

s <- c(sum(reg$employee == "1", na.rm = TRUE)*100/sum(reg$employee !="", na.rm = TRUE),
       sum(reg$employee == "2", na.rm = TRUE)*(100/2)/sum(reg$employee !="", na.rm = TRUE),
       sum(reg$employee_affect == "1", na.rm = TRUE)*100/sum(reg$employee_affect !="", na.rm = TRUE),
       sum(reg$employee_affect == "2", na.rm = TRUE)*(100/2)/sum(reg$employee_affect !="", na.rm = TRUE),
       sum(reg$employee_affect == "3", na.rm = TRUE)*(100/3)/sum(reg$employee_affect !="", na.rm = TRUE),
       sum(reg$employee_affect == "7", na.rm = TRUE)*(100/7)/sum(reg$employee_affect !="", na.rm = TRUE),
       sum(reg$employee_affect == "8", na.rm = TRUE)*(100/8)/sum(reg$employee_affect !="", na.rm = TRUE))

barplot(s,
        main = "ANSW. #3_1 ",              
        xlab = "Answers subpoints",         
        ylab = "Percetage",              
        ylim = c(0, 100),
        names.arg = c("Yes", "No",
                      "Not-at-all", "Slightly",
                      "Strongly", "DTA",
                      "Refusal"),
            col = "blue",  cex.names = 0.6)
}

您知道可能是什么问题吗?

enter image description here

0 个答案:

没有答案