One line of R shiny app not working as expected

I have the following line in my code:

matching_row_index <- which(apply(df1, 1, identical, row_df))

Here, row_df is a dataframe with only one row. df1 is another dataframe with many rows and exact same columns as row_df. I wish to find the index of that row in df1, which matches with the single row of row_df. This value of the index is to be given to matching_row_index. However, on running the code and using print statements, print(matching_row_index) gives output integer(0). Also other functionality in the app which depends on mathing_row_index is not working as expected. print(row_df) gave correct output as expected, so apparently row_df is fine.

Can someone please correct this line of code or explain what is causing the bug?

Hi @Saurish_Seksaria. I'm not exactly sure why your example fails, but below is an example that gets at the desired outcome in a slightly different way. I wrote a small function that checks for matching rows using the identical() function as you proposed, then step through each row of df1 using lapply().

# function to check rows for a match
check_rows = function(i, mydata, myrow) {
  identical(mydata[i,], myrow)
}

df1 = mtcars

# example trying to match the 7th row
row_df = mtcars[7,]
matching_row_index = which(lapply(1:nrow(df1), check_rows, df1, row_df) == T)
matching_row_index
#> [1] 7

# example trying to match the 23rd row
row_df = mtcars[23,]
matching_row_index = which(lapply(1:nrow(df1), check_rows, df1, row_df) == T)
matching_row_index
#> [1] 23

Created on 2023-09-25 with reprex v2.0.2.9000

it may be natural to use slider

df1 = mtcars
row_df = mtcars[7,]

library(slider)
which(slide_lgl(df1,
                \(x)identical(x,row_df)))

# Duster 360 
#         7

Thanks for the help. I'll try this out

Thanks for the help. I'll try this out too

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.