Reputation: 465
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. 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?
Upvotes: 0
Views: 426
Reputation: 206167
Well, the assign
is not necessary and is of the wrong syntax anyway (the second argument should be a character vector.
Try using this syntax instead
for(k in 1:length(states)){
state<-states[k]
print(k)
state.in <- d[[which(names(d)==tolower(state))]][["state.in"]]
state.out <- d[[which(names(d)==tolower(state))]][["state.out"]]
...
d[[which(names(d)==tolower(state))]][["state.in"]] <- state.in
d[[which(names(d)==tolower(state))]][["state.out"]] <- state.out
}}
Upvotes: 1