2014-06-06 42 views
-1

因此,我列出了一個列表作爲.rda文件。列表中有51個元素,對應於狀態縮寫,即「ca」,「fl」等。每個狀態都有一個state.in和state.out元素。因此,例如,有一長串遷移數據可作爲data_9495$ca$state.in訪問,另一個名爲data_9495$ca$state.out。爲了使這個巨大的數據文件與其他一些東西一致,我需要在數據文件中的每個狀態的state.in和state.out元素中更改一些值。該數據文件被稱爲data_9495,我需要實際更改列表中的元素,以便我可以重新保存數據文件並稍後使用它。我的想法是,它不一定「將」state.in/state.out「分配」到列表中,所以我嘗試使用assign但不工作。我至今是:(上點擊「數據9495.rda」頂部帶下劃線的東西) http://speedy.sh/vr7JQ/data-9495.rda列表到數據框和更改R中的一些值

的代碼,因爲它:

datafile<-"data_9495" 
datafile<-gsub("\\.rda$","",datafile) 
loaded_data <- load(paste("/Users/blah/blah/Listed  Data/", datafile, ".rda", sep="")) 
d<-get(loaded_data[1]) 
require("UScensus2010") 
data(countyfips) 
states<-unique(countyfips[,4]) 
for(k in 1:length(states)){ 
    state<-states[k] 
    print(k) 
state.in<-as.data.frame(d[[which(names(d)==tolower(state))]][1]) 
state.out<-as.data.frame(d[[which(names(d)==tolower(state))]][2]) 


{for(j in 1:dim(state.in)[1]) 
{ 
    if(state.in[j,3]=="63"&&state.in[j,4]=="050") 
     {state.in[j,3]<-state.in[j,1] 
     state.in[j,4]<-state.in[j,2]} 

} 
for(i in 1:dim(state.out)[1]) 
{ 
    if(state.out[i,3]=="63"&& state.out[i,4]=="050") 
     {state.out[i,3]<-state.out[i,1] 
     state.out[i,4]<-state.out[i,2]} 
} 
assign(d[[which(names(d)==tolower(state))]][1],state.in) 
assign(d[[which(names(d)==tolower(state))]][2],state.out) 
}} 

的.rda文件可以從以下網址下載將「運行」,但它似乎並沒有真正改變我需要改變的值。請注意,列類實際上是字符,這就是爲什麼我的for-loop if語句中有引號的原因。爲什麼這不會改變數據,我怎樣才能改變它呢?

+2

-1因爲不是[reproducible](http://stackoverflow.com/a/5963610/1412059)。提供數據,我們可以證明比這個可怕的for循環汞合金更好的選擇。 R不是C. – Roland

回答

0

試試這個。

d<-loaded_data 
require("UScensus2010") 
data(countyfips) 
states<-unique(countyfips[,4]) 

for (state in states) { 
    print(state) 
    include <- with(d[state][[1]],state.in[,3]=="63" & state.in[,4]=="050") 
    d[state][[1]]$state.in[include,3:4] <- d[state][[1]]$state.in[include,1:2] 
    include <- with(d[state][[1]],state.out[,3]=="63" & state.out[,4]=="050") 
    d[state][[1]]$state.out[include,3:4] <- d[state][[1]]$state.out[include,1:2] 
} 
相關問題