R cannot recognize an object that I already created in the same loop

I like to ask the question again if you have the time.

I present to you my regular df file, which I used earlier in previous previous Quesitons as a converted, simplified version of my real df data frame, which would be too difficult to show here. However, the main characteristics are the same.

id <-c(1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,3,3,3,3,3,3,3,3,3,3)
a <-c(3,1,3,3,1,3,3,3,3,1,3,2,1,2,1,3,3,2,1,1,1,3,1,3,3,3,2,1,1,3)
b <-c(3,2,1,1,1,1,1,1,1,1,1,2,1,3,2,1,1,1,2,1,3,1,2,2,1,3,3,2,3,2)
c <-c(1,3,2,3,2,1,2,3,3,2,2,3,1,2,3,3,3,1,1,2,3,3,1,2,2,3,2,2,3,2)
d <-c(3,3,3,1,3,2,2,1,2,3,2,2,2,1,3,1,2,2,3,2,3,2,3,2,1,1,1,1,1,2)
e <-c(2,3,1,2,1,2,3,3,1,1,2,1,1,3,3,2,1,1,3,3,2,2,3,3,3,2,3,2,1,4)
df <-data.frame(id,a,b,c,d,e)
df
df.list <- lapply(df[,2:6],function(x, id){ t(table(x, id, useNA = "ifany")) }, df$id)
df.list

You see, basically, what Ive created here is a combination of the total number of occurrences of each different number displayed in columns a and e and grouped by id identifiers in the id column at the same time.

In the next step, I created a loop that looks like this:

for (i in names(df.list))
{
  df.list[i]
  assign( paste("var",i,sep=""),
          (matrix(matrix(unlist(df.list[i])),ncol=nlevels(factor(df[,i])),nrow=3))/10
        )
}

, 10. , , , , STILL , , R →

vara
varb
varc
vard
vare

, "for (k in 1: 3)". , ( ).

for (i in names(df.list))
{
  df.list[i]
  assign( paste("var",i,sep=""),
          (matrix(matrix(unlist(df.list[i])),ncol=nlevels(factor(df[,i])),nrow=3))/10
        )

  for (k in 1:3)
    assign( paste("var",i,k,sep="."),
            vari[k,]*5 
          )
}

vari[k,]*5. ( .) , i . vara, varb, varc... .., , . : df, ( a e, a f a y ..

, :

Error in assign(paste("var", i, k, sep = "."), vari[k, ] * 5): object 'vari' not found

/ ? , , . ?

+3
3

,

vari[k,]*5 

get( paste( "var", i, sep="" ) )*5 

? , - , . , new.env ?

+1

@hadley, . , , .

@lazlo : R-ight way -

+1

vari , vara, varb, varc, vard,... . !

, , :

lapply(df.list,function(i) i/10*5)

, , . , , , . / .

> is.matrix(df.list[[1]])
[1] TRUE

, , :

VarList <- sapply(names(df.list),function(i){
  out <- df.list[[i]]/10*5

  out <- matrix(out,ncol(out)) # in case you want to drop all table attributes

  colnames(out) <- paste(
                     paste("var",i,sep=""),
                     1:ncol(out),
                     sep=".")
  out
},USE.NAMES=TRUE,simplify=FALSE)

, , . -

> VarList[["d"]][,1:2]
     vard.1 vard.2
[1,]    1.0    1.5
[2,]    1.0    3.0
[3,]    2.5    1.5

vars , - . , , .

+1

All Articles