-1

So I have a list of lists as an .rda file. There are 51 elements in the list, corresponding to the state abbreviations, i.e. "ca," "fl," etc. Each state has a state.in and state.out element. So for instance, there is a long list of migration data that can be accessed as data_9495$ca$state.in and another named data_9495$ca$state.out. In order to make this giant data file consistent with some other stuff, I need to change a few values in both the state.in and state.out elements of every state in the data file. The data file is called data_9495, and I need the elements of the list to actually be changed so I can resave the datafile and use it later. My thinking is that it doesn't necessarily "assign" the state.in/state.out to the list, so I tried using assign but that isn't working. What I have so far is:

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)
}}

The .rda file can be downloaded at: (click the underlined thing that says "data 9495.rda" at the top) http://speedy.sh/vr7JQ/data-9495.rda

The code as it is will "run" but it does not appear to actually be changing the values that I need changed. Note that the column classes are indeed characters, which is why there are quotations in my for-loop if-statements. Why isn't this changing the data, and how can I make it change it?

user3084629
  • 445
  • 2
  • 4
  • 7
  • 2
    -1 because not [reproducible](http://stackoverflow.com/a/5963610/1412059). Provide data and we can demonstrate far better alternatives than this horrible amalgam of `for` loops. R is not C. – Roland Jun 06 '14 at 13:45

1 Answers1

0

Try this.

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]
}
jlhoward
  • 58,004
  • 7
  • 97
  • 140