0

Here is my dataframe:

ID <- 1:4
var1 <- c("yes","no","yes","no")
var2 <- c("no","no","yes","no")
var3 <- c("yes","yes","no","no")
data <- data.frame(ID, var1, var2, var3)

I want to replace all of the yes by 1 and no by 0 in order to have such a table below

  ID var1 var2 var3
1  1    1    0    1
2  2    0    0    1
3  3    1    1    0
4  4    0    0    0

3 Answers 3

1

One solution would be across() from tidyverse:

library(tidyverse)
#Data
ID<-1:4
var1<-c("yes","no","yes","no")
var2<-c("no","no","yes","no")
var3<-c("yes","yes","no","no")
#Code
data<-data.frame(ID,var1,var2,var3,stringsAsFactors = F)
#Solution
data %>%
  mutate(across(c(var1:var3), ~ ifelse(.=='yes', 1, 0)))

Output:

  ID var1 var2 var3
1  1    1    0    1
2  2    0    0    1
3  3    1    1    0
4  4    0    0    0

And a base R solution would be using indexing with the values yes/no:

#Solution 2
data[data=='yes']<-1
data[data=='no']<-0
data[,-1] <- sapply(data[,-1],as.numeric)

Output:

  ID var1 var2 var3
1  1    1    0    1
2  2    0    0    1
3  3    1    1    0
4  4    0    0    0
Sign up to request clarification or add additional context in comments.

Comments

1

A base solution:

cbind(data[1], +(data[-1] == "yes"))

#   ID var1 var2 var3
# 1  1    1    0    1
# 2  2    0    0    1
# 3  3    1    1    0
# 4  4    0    0    0

Comments

0

Using data.table

library(data.table)
setDT(data)[, (2:4) :=  lapply(.SD, function(x) as.integer(x == 'yes')), .SDcols = 2:4]

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.