Home > Enterprise >  how to find the same value if their length are not the same?
how to find the same value if their length are not the same?

Time:11-30

I would like to find which row of a value that has the same value of another one? Here is the code:

> a
[1] 3 5 6
> num
     x  y z
1  112 55 0
2   23 21 1
3  121 56 2
4  132 15 3
5  123 15 4
6  132 45 5
7  132 41 6
8  179 45 7

To find out on which row of num has the same value that a has, is there a function I can use like match function? I tried this code (it would not work):

for(i in 1:length(num)){
  for (j in 1: length(a)){
    if (num$z[i]==a[j]){
      return(row(num[i]))
  }
 }
}

The outputs are the warning.

CodePudding user response:

See code below. lapply returns a list and the list which_rows contains the rows in which a value of a appears in each column.

which_rows <- lapply(df1, function(x) which(x %in% a))
which_rows 
$x
integer(0)

$y
integer(0)

$z
[1] 4 6 7

CodePudding user response:

You were almost there with the match function:

match(a, num$z)
# [1] 4 6 7

To get the full rows of num satisfying z==a:

num[match(a,num$z),]
#     x     y     z
#   132    15     3
#   132    45     5
#   132    41     6

or

num %>% filter(z %in% a)
#     x     y     z
#   132    15     3
#   132    45     5
#   132    41     6

To get just the y:

num$y[match(a,num$z)]
# [1] 15 45 41
  • Related