J. Pennycook J. Pennycook - 1 month ago 16
R Question

Subset Data with the assign Function in R

I'm new to programming in R (or at all), and I've been stuck on a problem for a few days. Apologies if this question already exists in some form, but I've looked as best I can and can't find anything.

I have multiple datasets called pop1, pop2, pop3, etc. and I'm trying to assign a value of zero to a specified subset of them from within a for loop. Through trial and error, I've found that the code:

subset(get(paste("pop", 1, sep = "")), ind == 46, select = -ind)


returns the subset I'm looking for, but when I try:

for (i in 1:3) {
assign(subset(get(paste("pop", i, sep = "")), ind == 46, select = -ind), 0)
}


I get the error message:

#Error in assign(subset(get(paste("pop", i, sep = "")), ind == 46, select = -ind), :
#invalid first argument


It seems to me that the assign function won't take subsets as its first argument, since none of the following work either:

assign(pop1[46, -1], 0)
assign(pop1$trait1, 0)
assign(subset(pop1, ind == 46), 0)


Is there a way I can make this work? Thanks very much, and let me know if more information would be helpful.

Answer

As mentioned in the comments its easier to do these kind of task via a list.

You can keep all your data sets in a list. Then using regular sub-setting, you can do regular assignments.

df1=data.frame(a=1:10,b=c(1,2))
df2=data.frame(a=1:10,b=c(1,2))
l=list(df1,df2)
lapply(l, function(x) { x[which(x[,2]==1),2]=999; return(x)})

If you like to do this in a loop then one can use parse along with eval.

for(i in 1:2){
    txt=paste('df',i,'[df',i,'[,2]==1,2]','=999', sep = "")
    eval(parse(text = txt))
}