Home > Software engineering >  How to change all numbers greater than 0 in a data frame to the character "present"?
How to change all numbers greater than 0 in a data frame to the character "present"?

Time:12-02

I just have a simply question which I tried to accomplish using mutate but wasn't very successful. I have a data frame with 2 rows and many columns which have numeric values from 0-1000. I just want to change non-zero numbers in every column to the word present and change those with 0 into the word absent.

My sample data frame is below

Cat Dog
5 0
0 5

which I want to turn to the following

Cat Dog
Present Absent
Absent Present

Thank You!

CodePudding user response:

We may create a logical matrix, convert to numeric index, replace with the vector of values based on the position index and assign back to the original dataset

df1[] <- c("Absent", "Present")[1   (df1 > 0)]

-output

> df1
      Cat     Dog
1 Present  Absent
2  Absent Present

data

df1 <- structure(list(Cat = c(5L, 0L), Dog = c(0L, 5L)), 
class = "data.frame", row.names = c(NA, 
-2L))

CodePudding user response:

Could use an ifelse statement:

df1 <- structure(list(Cat = c(5L, 0L), Dog = c(0L, 5L)), 
                 class = "data.frame", row.names = c(NA, -2L))

df2 <- ifelse(df1 == 0, "Absent","Present")
# or
df3 <- ifelse(df1 > 0, "Present", "Absent")
  • Related