无法使用for循环填充向量

时间:2014-01-27 05:03:36

标签: populate

我正在尝试使用for循环中的值填充空向量。但是我遇到了麻烦。请参阅下面的代码......

i <- c("AL", "AK", "AZ", "AR")
file <- read.csv("outcome-of-care-measures.csv", colClasses = "character")
mylist = list()
for i in unique(file$State){
    count = 1
    file <- file[grep(i[count], file$State),]
    head(file$State)
    file[,11] <- as.numeric(file[,11])
    head(file)
    R <- file[order(file[,2], na.last = TRUE),]
    head(R)
    Rsub <- R[,c(2,11)]
    head(Rsub)
    Rsub2 <- Rsub[order(Rsub[,2], na.last = TRUE),]
    head(Rsub2,20)
    Rsub2$Rank <- rank(Rsub2[,2], na.last=TRUE, ties.method="first")
    Rsub2 <- Rsub2[,-2]
    head(Rsub2,40)
    su <- subset(Rsub2, Rsub2$Rank==20)
    mylist <- su
    count = count + 1
}
}

我的最终输出只有一个变量的值

> mylist
                    Hospital.Name Rank
59 D W MCMILLAN MEMORIAL HOSPITAL   20

有人能指出我在哪里做错了吗?

由于

众议员

1 个答案:

答案 0 :(得分:0)

我自己想出来了......

file <- read.csv("outcome-of-care-measures.csv", colClasses = "character")
data <- data.frame()
for (i in unique(file$State)){
    #count = 1
    file1 <- file[grep(i, file$State),]
    head(file1$State)
    file1[,11] <- as.numeric(file1[,11])
    head(file1)
    R <- file1[order(file1[,2], na.last = TRUE),]
    head(R)
    Rsub <- R[,c(2,11)]
    head(Rsub)
    Rsub2 <- Rsub[order(Rsub[,2], na.last = TRUE),]
    head(Rsub2,20)
    Rsub2$Rank <- rank(Rsub2[,2], na.last=TRUE, ties.method="first")
    Rsub2 <- Rsub2[,-2]
    head(Rsub2,40)
    su <- subset(Rsub2, Rsub2$Rank==20)
    data <- rbind(data,su)
}