Home > Blockchain >  contingency table or dataframe to strings variable
contingency table or dataframe to strings variable

Time:01-15

I am afraid it is a basic question in R really but let's say I have a data set similar to a contingency table with a column of species information and characteristics. I want to put the species name with whatever value in the characteristics column and make empty if - present. How do I do it, kindly explain, if I can do it by for loop I will be getting a chance to learn more, even dplyr or other package is also fine?

df<-data.frame(Sp=c("Alphaproteobacteria", "Firmicutes", "Gamaproteobacteria","actino"),
               Starch=c(" ","-","-","1.5mm"),
               Gelation=c("-"," ","9mm","-"))

View(df):

df_New<-data.frame(Sp=c("Alphaproteobacteria", "Firmicutes", "Gamaproteobacteria","Actino"),
               Starch=c("Alphaproteobacteria","","","Actino"),
               Gelation=c("","Firmicutes","Gamaproteobacteria",""))

CodePudding user response:

You could mutate across the columns and check there if they have a - otherwise use the value of your sp column like this:

library(dplyr)
df %>%
  mutate(across(Starch:Gelation, ~ifelse(.x == "-", "", Sp)))
#>                    Sp              Starch           Gelation
#> 1 Alphaproteobacteria Alphaproteobacteria                   
#> 2          Firmicutes                             Firmicutes
#> 3  Gamaproteobacteria                     Gamaproteobacteria
#> 4              actino              actino

Created on 2023-01-14 with reprex v2.0.2

  • Related