根据R中的条件创建重复的行

编程入门 行业动态 更新时间:2024-10-08 07:36:48
本文介绍了根据R中的条件创建重复的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个数据表,看起来像这样

I have a data.table that looks like this

dt <- data.table(ID=c("A","A","B","B"),Amount1=c(100,200,300,400), Amount2=c(1500,1500,2400,2400),Dupl=c(1,0,1,0)) ID Amount1 Amount2 Dupl 1: A 100 1500 1 2: A 200 1500 0 3: B 300 2400 1 4: B 400 2400 0

我需要复制Dupl列中具有1的每一行,并在该重复的行中将Amount1值替换为Amount2值.除此之外,我需要在Dupl中为重复的行赋予值2.这意味着它应该像这样:

I need to duplicate each row that has a 1 in the Dupl column and replace the Amount1 value with the Amount2 value in that duplicated row. Besides that I need to give that duplicated row the value 2 in Dupl. This means it should look like this:

ID Amount1 Amount2 Dupl 1: A 100 1500 1 2: A 1500 1500 2 3: A 200 1500 0 4: B 300 2400 1 5: B 2400 2400 2 6: B 400 2400 0

非常感谢您的帮助! 亲切的问候,

Any help is much appreciated! Kind regards,

蒂姆

推荐答案

您可以尝试

rbind(dt,dt[Dupl==1][,c('Amount1', 'Dupl') := list(Amount2, 2)])

更多推荐

根据R中的条件创建重复的行

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

发布评论

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

>www.elefans.com

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