mercredi 21 juillet 2021

How to code for multiple ‘or’ conditions in an ifelse command for a dataframe in R

I am relatively new to R and I am attempting to add a column to a dataframe (called dGroup) which is conditional on the names specified in an existing column (Species) in the dataframe. There are a number of species that will belong to each of three groups to be specified in the dGroup column. These are “Mus (Mouse)” or “Cerc (Possum)” should generate a “SM” in the dGroup column, “Tri (Brush tail)” or “Thyl (Wallaby)” or “Mac (Bennetts)” should generate a “MM” in the dGroup column, and “Mac (Bennetts)” should generate a “LM” in the dGroup column. The dataframe looks like this:

|Record|Species|        dGroup|
|------|--------|-------|
|1|     Mus (Mouse)|
|2|     Cerc (Possum)|
|3|     Tri (Brush tail)
|4|     Thyl (Wallaby)
|5|     Vom (Wombat)
|6|     Mac (Bennetts)

The code I am using is as follows: #import csv ensuring character strings remain

    df <- read.csv(file = 'SH.csv', stringsAsFactors=FALSE)

#add a new column to the dataframe called dGroup

    df['dGroup']<-NA

#test with a single species note: this code words

    df$dGroup = ifelse(df$Species == "Mus (Mouse)","SM", "NA")

#test combine two species in an ‘or’ condition note: this code does not work

    df$dGroup = ifelse(df$Species == "Mus (Mouse)"||df$Species=="Cerc ( Possum)"){"SM", “NA”)}

I receive the following error: Error: unexpected '{' in Can anyone please help?

Aucun commentaire:

Enregistrer un commentaire