根据R中相等的行创建新列 [英] creating new column based on rows being equal in R
本文介绍了根据R中相等的行创建新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是一个简单的问题,关于在不同列中的一个列匹配条件中以行复制为条件创建新列。具体来说,如果行在对列中是重复的,则根据y列中等于/不等的行创建新列new。
Here is a simple question about creating a new column conditional on a row duplicate in one column matching criterion in different column. Specifically, if the row is a duplicate in column "pairs", create new column "new" based on rows in column "y" being equal/unequal.
在实际数据框我对其他列有更多条件,但我的主要问题是使这些条件依赖于对列中的行相同。
In the actual data frame I have even more conditions for other columns but my main issue is with making these conditions dependent on the rows being the same in the "pairs" column.
非常感谢!
pairs y new
1 1 1
1 0 1
2 1 0
2 1 0
3 3 1
3 1 1
推荐答案
假设值始终是成对的,即每组中只有两行:
Assuming values are always paired, i.e., there are only two row in each group:
DF <- read.table(text="pairs y new
1 1 1
1 0 1
2 1 0
2 1 0
3 3 1
3 1 1", header=TRUE)
library(plyr)
#for integers:
ddply(DF, .(pairs), transform, new1 = 1*(diff(y) != 0L))
#for numerics:
ddply(DF, .(pairs), transform, new1 = 1*(abs(diff(y)) > .Machine$double.eps ^ 0.5))
这篇关于根据R中相等的行创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文