用相应列的名称替换值 [英] Replace value with the name of its respective column

查看:40
本文介绍了用相应列的名称替换值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框:

Code    401k    CVS
101A            true
231N    true
FD54    true
99JB    
85F4    true

我正在尝试替换具有相应列名的 true字符值(例如 401k)。这是我想要的输出:

I'm trying to replace the "true" character values with the respective column name (e.g. "401k"). This is my desired output:

Code    401k    CVS
101A            CVS
231N    401k
FD54    401k
99JB    
85F4    401k


推荐答案

下面的代码使我能够将每个真值(字符)替换为其各自的列名。

The coding below enabled me to replace every "true" value (character) into its respective column name.

##Replace every "true" value with its respective column name
w <- which(df=="true",arr.ind=TRUE)
df[w] <- names(df)[w[,"col"]]

这篇关于用相应列的名称替换值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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