0

My question is so trivial, I want to paste a vector in a loop like this

 Mysheetlandscap <- excel_sheets("C:/FAPSEP_Eucalyptus/FAPSEP/AHMED_GDAY/CloneParnew5_forCALIB2.xlsx")

for(j in 1:length(Mysheetlandscap)){

  ClonePar <- read_excel("C:/FAPSEP_Eucalyptus/FAPSEP/AHMED_GDAY/CloneParnew5_forCALIB2.xlsx", sheet = Mysheetlandscap[j])

  x <- ClonePar$,j,[!is.na(ClonePar$MIN_CL)]  #should return the vector ClonePar$j
  }

So I tried

get(paste0("ClonePar$",j))

Error in get(paste0("ClonePar$", j)) : object 'Cal_OCT_18_GLM$C041H' not found

What I'm missing?

5
  • Maybe ClonePar[[3]]. Commented Oct 16, 2018 at 14:42
  • Should iterate j in the loop Commented Oct 16, 2018 at 14:46
  • 1
    I don't recognize your syntax with $,j, When looping you typically need to fill an empty list x <- list() and then have the looping index specified when you fill it with a loop ClonePar[j] <- read_excel("C:/FAPSEP_Eucalyptus/FAPSEP/AHMED_GDAY/CloneParnew5_forCALIB2.xlsx", sheet = Mysheetlandscap[j]) Also is x outside of your loop, it isn't clear since you don't have a terminal } Commented Oct 16, 2018 at 14:49
  • x is inside the loop and I need to assign the vector: ClonePar$,j,[!is.na(ClonePar$MIN_CL)] to x inside the loop Commented Oct 16, 2018 at 14:52
  • 1
    @AhmedAttia Yes, and do like EJJ says. Create ClonePar <- list() outside the loop. Then, inside the loop use j to assign values: ClonePar[[j]] <- whatever. Commented Oct 16, 2018 at 14:59

2 Answers 2

1

note: I used seq_along instead of 1:length() so that you don't get any funky output if you have an empty data frame

If you want to use a for loop:

ClonePar <- list() #create empty list

for(j in seq_along(Mysheetlandscap)){

  ClonePar[j] <- read_excel("C:/FAPSEP_Eucalyptus/FAPSEP/AHMED_GDAY/CloneParnew5_forCALIB2.xlsx", sheet = Mysheetlandscap[j])

}

ClonePar[[1]] #look the first element (a data frame) in your newly filled list

If you want to use the apply family (based on Vladimir's answer):

ClonePar <- lapply(seq_along(Mysheetlandscap),
                   function(j) read_excel("C:/FAPSEP_Eucalyptus/FAPSEP/AHMED_GDAY/CloneParnew5_forCALIB2.xlsx", sheet = j))

in the case of using lapply you don't have to create an empty list before running the vectorized operation.

Sign up to request clarification or add additional context in comments.

Comments

0

It's hard to understand... But maybe it is what you want:

ClonePar <- lapply(1:length(Mysheetlandscap), function(j)
read_excel("C:/FAPSEP_Eucalyptus/FAPSEP/AHMED_GDAY/CloneParnew5_forCALIB2.xlsx", sheet = j))

j<-10
x <- ClonePar[[10]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.