Identify value in 1 column corresponding to equal values in two another columns by row

谁说我不能喝 提交于 2019-12-24 17:42:48

问题


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. 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. 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

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
} 

and which(df1[,2] == (df1[,3]), arr.ind = TRUE) returns the number of row, not the value in V1.

Thank you !


回答1:


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


来源:https://stackoverflow.com/questions/33160257/identify-value-in-1-column-corresponding-to-equal-values-in-two-another-columns

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!