There is no object with the name "india_i". We don't have any information about what is in the "crimes" vector but if it's the numbers 1:12 then the objects have names like "india_1". You should learn to make named lists, rather than using separate objects.
After your edit, we can demonstrate this using a slightly modified version of your code ( and adding the missing close-parenthesis for the sum
-call).
India_L <- list() # create an (empty) master list
for (i in crs){
assign(paste("india_",i,sep=""),rep(NA,3))
for (j in 1:3){
India_L[[paste("india_",j,sep="")]] <-sum(total[yrs==yr[j]&crs==cr[i]])
}
}
India_L # print to see the structure
#---- result
$india_1
[1] 0
$india_2
[1] 0
$india_3
[1] 0
The reason you got all zeroes was that there are no levels for the yrs column of the cri
-object. It was "numeric" and only "factor"-classes have levels in R. A comment on your strategy. I wasn't really sure what goal you had set for yourself (besides) getting the assign
function to succeed. The sum
of those logical tests didn't seem particularly informative. Perhaps you meant to use the %in%
operator. Using ==
with a vector will not generally be informative.
Using attach
is generally very unwise. Notice the warning you got:
> attach(cri)
The following objects are masked _by_ .GlobalEnv:
crs, sts, total, yrs
The following objects are masked from cri (pos = 3):
crs, sts, total, yrs
So the objects named might be changed with an edit:
sts <- c(rep("s1.a",9),rep("s2.a",9))
What object do you think was altered? And if you then detach
-ed the cri
-dataframe, where do you think the edit would reside? One of the big problems with attaching objects is that the user gets confused about what is actually being changed.
It would be more clear to create the values with the dataframe in one pass and then work on components of the dataframe:
cri <- data.frame(
sts = c(rep("s1",9),rep("s2",9)),
yrs = c(1,1,1,2,2,2,3,3,3,1,1,1,2,2,2,3,3,3),
crs = c("a","b","c","a","b","c","a","b","c"),
total = c(1:18) )