'get() returns error "target of assignment expands to non-language object"

I need some help with R. I'm trying to create variables on a loop, naming them based on i of the loop and then use them on said loop. The problem is I can't seem to find a solution to then use those variables in each loop. As you can see below on the code, I tried paste0() and get(), but I soon found out that I cannot use get() to use these variables as the error "target of assignment expands to non-language object" will pop up.

for (i in seq(0.90, 1, by = 0.01)){
  otus<-otu(dnabin,k=5,  threshold = i, method = "centroid",residues = NULL)
  max(otus)
  #### check if differente from the number of species
  df_otu<-data.frame(as.list(otus))
  df_otu2<-melt(df_otu)
  df_otu2$variable<-gsub("\\.","",df_otu2$variable)
  df_otu2$variable<-gsub('[0-9]+', '', df_otu2$variable)
  df_otu2$variable<-gsub('\\_', ' ', df_otu2$variable)
  
  test_df <- df_otu2 |>
    group_by(variable) |>
    summarise(distincts = n_distinct(value))
  
  test_df2 <- df_otu2 |>
    group_by(value) |>
    summarise(distincts = n_distinct(variable))
  
  name <- paste0("otu_1_", i)
  assign(name, left_join(df_otu2,test_df,by="variable"))
  name <- paste0("otu_2_", i)
  assign(name, left_join(get(paste0("otu_1_", i)),test_df2,by="value"))
  names(get(paste0("otu_2_", i)))<-c("species","OTU","number_of_OTUs_per_species","number_of_species_in_OTU")
  
  get(paste0("otu_2_", i))<-get(paste0("otu_2_", i)) %>%
    mutate(grade = ifelse(number_of_species_in_OTU>1,"ambiguous",
                          ifelse(number_of_OTUs_per_species>1 & number_of_species_in_OTU==1,"semi_ambiguous",
                                 ifelse(number_of_OTUs_per_species==1 &  number_of_species_in_OTU==1,"unambiguous","needs_update"))))
  
  dominant_grade <- "ambiguous"
  dt <- as.data.table(get(paste0("otu_2_", i)))
  dt[, contains_dominant := any(grade == dominant_grade), by=species]
  dt[contains_dominant == TRUE, grade := dominant_grade]
  get(paste0("otu_2_", i)) <- setDF(dt) 

This is part of the loop. The error is in:

names(get(paste0("otu_2_", i)))<-c("species","OTU","number_of_OTUs_per_species","number_of_species_in_OTU")

But I know the next line won't run as well because of the same error. Is there a way to go around it each time I need to get and use the variable? Thank you.

r


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source