[英]Identify value in 1 column corresponding to equal values in two another columns by row
I am sure that my question is quite simple but I couldn't figure out the solution. 我确信我的问题很简单,但我不知道解决方案。
I want to check my table by rows. 我想按行检查我的表。 If two columns (V2, V3) have the same value in the same row I want to extract the value in the corresponding column V1 and add it to my table.
如果两列(V2,V3)在同一行中具有相同的值,我想提取相应列V1中的值并将其添加到我的表中。 Thus:
从而:
my data 我的资料
m <- matrix(c(1,2,3,5,6,0,0,0,1,3,5,4,1,1,2), 5, 3)
df1<-as.data.frame(m)
> df1
V1 V2 V3
1 1 0 5
2 2 0 4
3 3 0 1
4 5 1 1
5 6 3 2
I want to compare V2 and V3. 我想比较V2和V3。 The same values (1,1) are in row 4, so I want to obtain value 5 from V1.
相同的值(1,1)在第4行中,因此我想从V1获得值5。 and write it to V4.
并将其写入V4。 All other values can become NA.
所有其他值都可以变为NA。 Expected result:
预期结果:
> df1
V1 V2 V3 V4
1 1 0 5 NA
2 2 0 4 NA
3 3 0 1 NA
4 5 1 1 5
5 6 3 2 NA
I know that I can select the specific row by df1[df1$V2 == max(df1$V2), ]
, but what if I need just the first value, not the whole row? 我知道我可以通过
df1[df1$V2 == max(df1$V2), ]
选择特定的行,但是如果我只需要第一个值而不是整个行怎么办? My if loop doesn't work... 我的if循环不起作用...
newcol <- vector()
for (i in 1:nrow(df1)) {
thematch <- which(df1[,1] == max(df1[,3]))
newcol<-thematch
}
and which(df1[,2] == (df1[,3]), arr.ind = TRUE)
returns the number of row, not the value in V1. 并且
which(df1[,2] == (df1[,3]), arr.ind = TRUE)
返回行数,而不是V1中的值。
Thank you ! 谢谢 !
I guess you can do this: 我想你可以做到这一点:
df1$V4 <- with(df1, V1[ifelse(V2==V3, TRUE, NA)] )
V1 V2 V3 V4
1 1 0 5 NA
2 2 0 4 NA
3 3 0 1 NA
4 5 1 1 5
5 6 3 2 NA
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.