根据其他列设置列的值

编程入门 行业动态 更新时间:2024-10-25 11:18:20
本文介绍了根据其他列设置列的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

根据其他列设置列的值

本文发布于:2023-05-29 23:05:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/355030.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!