jeudi 30 avril 2020

If else loop over list with conditionals matching a character pattern R

I have a list with several dataframes. I want to write a loop iterating this list and modifying the dataframes based on their title. In general I want to: 1. add a column (trait, protein, metabolite) with their name. my.files is a string with all the names 2. add a column with the calculated standard deviation 3. add a column with the calculated degrees of freedom

for (i in 1:length(list.txt)){
if (i %in% 'Height.txt'){

  list.txt[[i]][,'trait'] <- 'complex' #add trait name
  list.txt[[i]][,'sd'] <- (list.txt[[i]][,'SE']*sqrt(list.txt[[i]][,'N'])) #calculate sd
  list.txt[[i]][,'df'] <- list.txt[[i]][,'N']-2 #add df

} else if (i %in% 'Folkersen*') {

  nam <- paste(my.files[[i]])
  list.txt[[i]] <- assign(nam, list.txt[[i]])
  list.txt[[i]][,'protein'] <- my.files[[i]] #add trait name
  list.txt[[i]][,'N'] <- 3394 #add N
  list.txt[[i]][,'sd'] <- (list.txt[[i]][,'SE']*sqrt(list.txt[[i]][,'N'])) #calculate sd
  list.txt[[i]][,'df'] <- list.txt[[i]][,'N']-2 #add df

}  else {

  nam1 <- paste(my.files[[i]])
  assign(nam1, list.txt[[i]])
  list.txt[[i]][,'metabolite'] <- my.files[[i]] #add trait name
  list.txt[[i]][,'sd'] <- (list.txt[[i]][,'se'] *sqrt(list.txt[[i]][,'n_samples'])) #calculate sd
  list.txt[[i]][,'df'] <- list.txt[[i]][,'n_samples']-2 #add df

}
}

This code returns 'Error in [.data.table(list.txt[[i]], , "se") : column(s) not found: se' and also doesn't recognize 'n_samples'. When these commands are switched off the code returns no errors, but doesn't change anything in the list. I am not sure what i'm doing wrong here, but I assume it has something to do with the conditionals.

Aucun commentaire:

Enregistrer un commentaire