replace Yes, No to 1, 0 in multiple columns in r [duplicate]

风格不统一 提交于 2021-02-17 07:03:34

问题


I need to replace the Yes and No values to 1 and 0 in 200 columns.

I was using with the command

data %>% mutate(x=ifelse(x=="Yes", 1,0))

but i have to go through each column at a time, and i was wondering if there was any way i could do it all at once.


回答1:


You may use ifelse on the entire data frame:

df <- data.frame(v1=c("Yes","No"), v2=c("No","Yes"), stringsAsFactors=FALSE)
ifelse(df == "Yes", 1, 0)

     v1 v2
[1,]  1  0
[2,]  0  1

This coerces to a matrix, but given that your output would be completely numeric, maybe this doesn't matter to you.




回答2:


This is the dplyr version (since your using it anyway).

Just put your calculation in a function...

helperFunction <- function(x){
    ifelse(x=="Yes", 1,0)
}

...and then you can apply this function to every column.

data %>%
    mutate_all(helperFunction)



回答3:


Following Tim Biegeleisen's answer, stating that a function can be used on the entire dataframe, this code works:

data <- data.frame(v1=c("Yes","No"), v2=c("No","Yes"))

data[] <- as.integer(data == "Yes")

data
#  v1 v2
#1  1  0
#2  0  1

And it's probably faster than ifelse, which can be useful with a 200 column dataframe.




回答4:


You can try the following code

df[] <- +(df == "Yes")

and you will get

> df
  col1 col2
1    1    0
2    0    1
3    1    1

DATA

df <- structure(list(col1 = c(1L, 0L, 1L), col2 = c(0L, 1L, 1L)), row.names = c(NA, 
-3L), class = "data.frame")


来源:https://stackoverflow.com/questions/59785995/replace-yes-no-to-1-0-in-multiple-columns-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!