根据其他列设置列的值 [英] Set values of column based on other column

查看:90
本文介绍了根据其他列设置列的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的数据框:

I have a data frame which looks like this:

  ID     Score New.ID New.Score
  123     5      456          
  456     1      789          
  789     0      123   

我想给New.ID列提供相同的分数(只是顺序不同).

I would like to give the same scores to the New.ID column (which are just in a different order).

所需结果:

  ID    Score New.ID New.Score
  123     5      456         1
  456     1      789         0
  789     0      123         5

用于重构数据帧的代码:

Code to reconstruct data frame:

ID <- as.factor(c(123,456,789))
Score <- c(5,1,0)
New.ID<- as.factor(c(456, 789, 123))
New.Score <- c(1,0,5)
dt <- data.frame(ID, Score, New.ID, New.Score)

更新

所需的输出:

  Group  ID Score New.ID New.Score
     1 123     5    456         1
     1 456     1    789         0
     1 789     0    123         5
     2 555     1    999         0
     2 123     1    123         1
     2 999     0    555         1

因此,我试图尝试对每个组使用该功能. ID 123在组1中的得分为5,但在组2中其得分为1.而且我只想使用每个组中显示的分数.

So I am trying to attempt to use the function for each group. The ID 123 has score 5 in group 1, but in group 2 it has score 1. And I only want to use the scores that appear within each group.

我尝试使用ave:

mtch <- function(x) {
  dt[match(x,dt$ID),"Score"]  
}

dt$New.Score <- ave(dt$New.ID, dt$Group, FUN = mtch)

但是它给了我NA值.

第二个df的代码:

Group <- as.factor(c(1, 1, 1, 2, 2, 2))
ID <- as.factor(c(123,456,789, 555, 123, 999))
Score <- c(5,1,0, 1,1,0)
dt <- data.frame(Group, ID, Score, New.ID)

推荐答案

简单的match应该可以解决问题.使用您提供的数据:

A simple match should do the trick. Using the data you provided:

data <- data.frame(ID, Score, New.ID)
data$New.Score <- data[match(data$New.ID,data$ID),"Score"]

然后检查它是否是我们想要的结果:

And then checking that it's our desired result:

identical(dt,data)
#[1] TRUE

这篇关于根据其他列设置列的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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