我有一个向量,称为“状态”,所有状态均带有2个字母的缩写,以及一个temp1数据帧,其中包含3列“ Hospital.Name”,“心脏病”和“ State”
temp1 Hospital.Name heart attack State
99 PROVIDENCE ALASKA MEDICAL CENTER 13.4 AK
103 ALASKA REGIONAL HOSPITAL 14.5 AK
102 FAIRBANKS MEMORIAL HOSPITAL 15.5 AK
temp1表在每个州都有更多的医院
states
[1] "AK" "AL" "AR" "AZ" "CA" "CO" "CT" "DC" "DE" "FL" "GA" "GU" "HI" "IA" "ID" "IL" "IN" "KS" "KY" "LA" "MA" "MD" "ME" "MI" "MN" "MO" "MS"
[28] "MT" "NC" "ND" "NE" "NH" "NJ" "NM" "NV" "NY" "OH" "OK" "OR" "PA" "PR" "RI" "SC" "SD" "TN" "TX" "UT" "VA" "VI" "VT" "WA" "WI" "WV" "WY
当我使用“状态”数组的第一个值单独运行此代码时,我得到了正确的结果
resulttest <- subset(temp1[1,], State ==states[1])
resulttest
Hospital.Name heart attack State
99 PROVIDENCE ALASKA MEDICAL CENTER 13.4 AK
但是当我尝试对“状态”向量中的所有状态循环运行时,我得到一个NULL值
for (i in 1:length(states)){
resulttest <- subset(temp1[1,], State ==states[i])
}
# > resulttest
#
# [1] Hospital.Name heart attack State
# <0 rows> (or 0-length row.names)
有人可以帮我循环功能吗?,谢谢
答案 0 :(得分:0)
这是我最终在注释的帮助下所做的事情,还将结果附加到称为“结果”的新数据框中,num是变量。感谢您的帮助:)
是变量
result <- data.frame(matrix(ncol = 3, nrow = 0))
x <- c("Hospital.Name", "heart attack", "State")
colnames(result) <- x
for (i in 1:length(states)){
resulttest <- temp1[temp1$State %in% states[i],]
result[i,] <-resulttest1[num,]
}