Reputation: 4090
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 !
Upvotes: 1
Views: 1486
Reputation: 66819
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
Upvotes: 2