【发布时间】:2014-06-06 13:17:46
【问题描述】:
所以我有一个列表作为 .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 但这不起作用。到目前为止我所拥有的是:
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 文件可以在以下位置下载:(单击顶部带有下划线的“data 9495.rda”) http://speedy.sh/vr7JQ/data-9495.rda
代码将“运行”,但它似乎并没有真正改变我需要改变的值。请注意,列类确实是字符,这就是我的 for 循环 if 语句中有引号的原因。为什么这不会改变数据,我怎样才能让它改变它?
【问题讨论】:
-
-1 因为不是reproducible。提供数据,我们可以展示比
for循环的这种可怕的混合物更好的选择。 R 不是 C。