Home > database >  Using a loop to create a new column and fill the items based on matching
Using a loop to create a new column and fill the items based on matching

Time:01-13

I have a data frame and I tried to use a for loop to create a new column and fill it with gram negative and gram positive by matching species in column 2. I know how to do with dplyr, but I want to use loop to improve my understanding for coding. here is my code:

species_abundance<-data.frame(
ID=c(1,2,3,4,5),
Genus = c("Sphingopyxis marina","Loktanella salsilacus",
          "Paracoccus chinensis","Bacillus","Streptomyces"))
 

and output is like

species_abundance<-data.frame(
ID=c(1,2,3,4,5),
Genus = c("Sphingopyxis marina","Loktanella salsilacus",
          "Paracoccus chinensis","Bacillus","Streptomyces")),
Grams_staining=c("grams_negative, grams_negative, grams_negative,grams_positive, grams_positive)

I tried with this code, but I didnt get my expected results, kindly help me in what all way we can loop to get results, so I can improve my learning.

for(i in 1:nrow(species_abundance)) {# for-loop over columns
  if (species_abundance[i,2] == "Sphingopyxis marina"&&
      species_abundance[i,2] == "Loktanella salsilacus"&&
      species_abundance[i,2] == "Paracoccus chinensis"){
      print("grams_negative")
  }
  
  else {
    species_abundance[i,2] == "Bacillus"{
     print("grams_positive")
  }  
}

CodePudding user response:

I would suggest this approach. First, define which genus/species should be identified as gram positive and gram negative, then use %in% in your for loop to print:

Define gram positive/negative (based on your loop in your question, can be anything).

gramneg <- c("Sphingopyxis marina", "Loktanella salsilacus", "Paracoccus chinensis")
grampos <- c("Bacillus", "some_other_genus")

For loop

for(i in seq_along(species_abundance$Genus)){
  if(species_abundance$Genus[i] %in% gramneg){
    print("gram_negative")
  } else {
    if(species_abundance$Genus[i] %in% grampos){
    print("gram_positive")}
     else {
    print("Not in in gram positive or gram negative list")
     }
    }
}

Output:

# [1] "gram_negative"
# [1] "gram_negative"
# [1] "gram_negative"
# [1] "gram_positive"
# [1] "Not in in gram positive or gram negative list"

Data

species_abundance <- data.frame(ID = c(1,2,3,4,5),
                                Genus = c("Sphingopyxis marina","Loktanella salsilacus",
                                          "Paracoccus chinensis","Bacillus","Streptomyces"))
  • Related