逐行标识1列中的值,该值对应于另外两列中的相等值 [英] 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.
我想按行检查我的表.如果两列(V2,V3)在同一行中具有相同的值,我想提取相应列V1中的值并将其添加到我的表中.因此:
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. Thus:
我的数据
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
我想比较V2和V3.相同的值(1,1)在第4行中,因此我想从V1获得值5.并将其写入V4.所有其他值都可以变为NA.预期结果:
I want to compare V2 and V3. The same values (1,1) are in row 4, so I want to obtain value 5 from V1. and write it to V4. All other values can become 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
我知道我可以通过 df1 [df1 $ V2 == max(df1 $ V2),]
选择特定的行,但是如果我只需要第一个值而不是整个行怎么办??我的if循环不起作用...
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? My if loop doesn't work...
newcol <- vector()
for (i in 1:nrow(df1)) {
thematch <- which(df1[,1] == max(df1[,3]))
newcol<-thematch
}
和 which(df1 [,2] ==(df1 [,3]),arr.ind = TRUE)
返回行数,而不是V1中的值.
and which(df1[,2] == (df1[,3]), arr.ind = TRUE)
returns the number of row, not the value in V1.
谢谢!
推荐答案
我想您可以做到:
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
这篇关于逐行标识1列中的值,该值对应于另外两列中的相等值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!