将 r 中的多列中的 Yes, No 替换为 1, 0 [英] replace Yes, No to 1, 0 in multiple columns in r

查看:93
本文介绍了将 r 中的多列中的 Yes, No 替换为 1, 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将 200 列中的 Yes 和 No 值替换为 1 和 0.

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

我正在使用命令

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.

推荐答案

您可以对整个数据框使用 ifelse:

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.

这篇关于将 r 中的多列中的 Yes, No 替换为 1, 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆