3

I have a class column in my data frame which carries the value "Bad" & "Good". I want to replace these string into 0 & 1 respectively.

I tried the following:

 x = c("Bad", "Good", "Bad", "Bad", "Good")

factor(x)

factor(x, c(0, 1))

but, it converts the value in the dataset to NA

factor(x, c(0, 1))

[1] <NA> <NA> <NA> <NA> <NA>`
Levels: 0 1`
2
  • 8
    as.integer(x=="Good") . Yours doesnt work as factor looks for levels 0/ 1 which arent there. So be explicit factor(x, levels=c("Bad", "Good"), labels=c(0, 1)) Commented Jul 20, 2017 at 15:08
  • 1
    It worked. Thanks :) Commented Jul 20, 2017 at 15:12

2 Answers 2

7

A convenient tidyverse approach would be to use dplyr's recode function.

df <- data.frame(x = c("Bad", "Good", "Bad", "Bad", "Good"))
df$x <- as.factor(df$x)

library(tidyverse)
df <- df %>% 
    mutate(x = recode(x, 
                      "Bad" = "0", 
                      "Good" = "1"))

That's assuming you want to keep it as a factor column. If you'd rather it be a numeric vector you'd simply add a second mutate call to convert it to numeric... EDIT: being careful to convert the values as numbers, not the underlying level codes.

df <- df %>% 
  mutate(x = recode(x, 
                    "Bad" = "0", 
                    "Good" = "1")) %>% 
  mutate(x = as.numeric(levels(x))[x])
Sign up to request clarification or add additional context in comments.

Comments

1

You can use a named vector to map the text strings to numeric values.

df <- data.frame( x = c("Bad", "Good", "Bad", "Bad", "Good"), stringsAsFactors = FALSE)

lookup <- c("Bad" = 0, "Good" = 1)

df$new_x <- lookup[df$x]

Result

df
     x new_x
1  Bad     0
2 Good     1
3  Bad     0
4  Bad     0
5 Good     1


# showing type info
str(df)
'data.frame':   5 obs. of  2 variables:
 $ x    : chr  "Bad" "Good" "Bad" "Bad" ...
 $ new_x: num  0 1 0 0 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.