r - 替换列中的值 [英] r - Replace values in columns

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

问题描述

我有一个数据框:

    V1 V2 V3 V4 V5 V6 V7
a   F  B  C  D  B  A  T
b   R  D  C  D  F  A  T
c   A  C  C  R  F  A  T

在每一行中,我想用 V1 列中的值替换与 V2 列匹配的 V3:V7 列中的值.它应该是这样的.

In every row I want to replace values in columns V3:V7 that matches column V2 with value in column V1. It should look like this.

   V1 V2 V3 V4 V5
a  C  D  F  A  T
b  C  R  F  A  T
c  A  R  F  A  T

我该怎么做?

推荐答案

这是另一种使用 lapply 的方法:

Here is another method using lapply:

df[, 3:7] <- lapply(df[,3:7], function(i) {i[i == df$V2] <- df$V1[i == df$V2]; i})

df
  V1 V2 V3 V4 V5 V6 V7
a  F  B  C  D  F  A  T
b  R  D  C  R  F  A  T
c  A  C  A  R  F  A  T

对于每个变量,使用子集替换匹配项.

For each variable, matches are substituted using subsetting.

同样的方法可以用于replace函数:

This same method may be used the the replace function:

df[, 3:7] <- lapply(df[,3:7],
                    function(i) replace(i, i == df$V2, df$V1[i == df$V2]))

与@mr-rip 的解决方案一样,这些变量必须存储为字符,而不是其工作的因素.

As with the solution of @mr-rip, these variables must be stored as character and not factor for this to work.

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

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