Import csv file and change names of certain values

Hi,

Okay so my problem is that I want to import a csv file (that is separeted by commas, so R reads it as a dataframe).

The first coloumn is called "Animals", and below there is "crocodile", "elaphant" etc.
Here I want to replace names of the animals to be either "reptile" or "mammal".

How do I do this?

Thank you a lot in advance

One possible method is to use the case_when() function from dplyr combined with vectors defining which animals are in which class.

library(dplyr)

DF <- data.frame(Animal=c("Elephant","Snake","Crocodile","Dog"),
                 Values=1:4)
DF
#>      Animal Values
#> 1  Elephant      1
#> 2     Snake      2
#> 3 Crocodile      3
#> 4       Dog      4
MAMMALS <- c("Elephant", "Dog")
REPTILES <- c("Crocodile", "Snake")
DF<- DF |> mutate(Animal = case_when(
  Animal %in% MAMMALS ~ "Mammal",
  Animal %in% REPTILES ~ "Reptile",
  TRUE ~ "Not Found"
))
DF
#>    Animal Values
#> 1  Mammal      1
#> 2 Reptile      2
#> 3 Reptile      3
#> 4  Mammal      4

Created on 2022-07-26 by the reprex package (v2.0.1)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.