CuriousDude
CuriousDude

Reputation: 1117

R, change a character string in dataframe to binary values

My dataframe has a column called "LandType" of characters, either "Rural" or "Urban" for a bunch of samples. All I want to do is convert them to 1's and 0's, where "Rural" is 1, and "Urban" is 0.

I thought it would as simple as:

data$LandType[data$LandType == "Rural"] <- 1
data$LandType[data$LandType == "Urban"] <- 0

But after running this with no errors and then checking my data df, the crazy thing is that ONLY "Rural" has changed to 1's but Urban still remains as a string. I tried with different numbers but same thing happened, only Rural would change to the value I assigned.

Upvotes: 0

Views: 2575

Answers (4)

GKi
GKi

Reputation: 39657

In my case your way works:

set.seed(42)
data <- data.frame(LandType = sample(c(rep("Rural", 72), rep("Urban", 93))))

data$LandType[data$LandType == "Rural"] <- 1
data$LandType[data$LandType == "Urban"] <- 0

table(data$LandType)
# 0  1 
#93 72

To get binary values I would recommend to use the type logical (TRUE or FALSE).

data$LandType <- data$LandType == "Rural"

In case 0 and 1 is needed just add a +

data$LandType <- +(data$LandType == "Rural")

Upvotes: 0

akrun
akrun

Reputation: 887068

We could use as.integer

data$Landtype <- as.integer(data$Landtype == "Rural")

data

data = data.frame(Landtype = c("Rural", "Urban", "Rural", "Urban"))

Upvotes: 0

rjen
rjen

Reputation: 1972

A tidyverse option using recode()

library(dplyr)

mutate(data, Landtype = recode(Landtype, Rural = 1, Urban = 0))

# # A tibble: 4 x 1
# Landtype
# <dbl>
# 1        1
# 2        0
# 3        1
# 4        0

Data

data <- tibble(Landtype = c("Rural", "Urban", "Rural", "Urban"))

Upvotes: 2

Nad Pat
Nad Pat

Reputation: 3173

Just use ifelse

#your data
data = data.frame(Landtype = c("Rural", "Urban", "Rural", "Urban"))
#ifelse condition 
data$Landtype = ifelse(data$Landtype == "Rural", 1,0)

Upvotes: 4

Related Questions