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")
}
}
if .. && .. &&construct requires that something matches ALL of those, not one of those. I would tryif(species_abundance$Genus[i] %in% c("Sphingopyxis marina", "Loktanella salsilacus", "Paracoccus chinensis")). You also need a way to allocate the result to the data frame (e.g.species_abundance$Grams_staining[i] <-)Grams_staining. Kindly explain the solution Thanksmydata <- mydata[,c(3,1,2)]to select which columns to keep and in which order.