识别值是否由R中的组重复 [英] Identify if a value is repeated or not by groups in R
本文介绍了识别值是否由R中的组重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含许多列和行的数据.我想确定是否通过创建新的逻辑变量为组重复(相同)一个值.
I have a data with many columns and rows. I would like to identify if a value is repeated (the same) for a group or not with a creation of a new logical variable.
所以我的数据如下:
v0 <- c(1,2,3,4,5,6,7,8,9)
v1 <- c("a", "b", "a", "c","e", "c", "b", "b", "e")
v2 <- c("R", NA, "R", "R", "G","C", "R", "R", "G")
dftest <- data.frame(v0, v1, v2)
v0 v1 v2
1 1 a R
2 2 b <NA>
3 3 a R
4 4 c R
5 5 e G
6 6 c C
7 7 b R
8 8 b R
9 9 e G
我需要以相同的v1值是否采用相同的v2值的方式比较v1和v2的值.所以我的输出df看起来像这样:
I need to compare the values of v1 and v2 in a way whether the same v1 values take a same v2 values or not. So my output df would look like this:
v3 <- c(T, F, T, F, T, F, F, F, T )
dfresult <- data.frame(v0, v1, v2, v3)
v0 v1 v2 v3
1 1 a R TRUE
2 2 b <NA> FALSE
3 3 a R TRUE
4 4 c R FALSE
5 5 e G TRUE
6 6 c C FALSE
7 7 b R FALSE
8 8 b R FALSE
9 9 e G TRUE
任何不屑一顾将不胜感激.谢谢.
Any saggestion would be appreciated. Thanks.
推荐答案
这是基本的R解决方案,其中使用了 ave
Here is a base R solution, where ave
is used
dfresult <- within(dftest, v3 <- as.logical(ave(as.vector(v2),v1,FUN = function(x) length(unique(x))==1)))
如此
> dfresult
v0 v1 v2 v3
1 1 a R TRUE
2 2 b <NA> FALSE
3 3 a R TRUE
4 4 c R FALSE
5 5 e G TRUE
6 6 c C FALSE
7 7 b R FALSE
8 8 b R FALSE
9 9 e G TRUE
这篇关于识别值是否由R中的组重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文