R - error when matrix indexing a dataframe

Viewed 33

I am trying to replicate the answer in this post: Index a data frame row-by-row using column names selected from a variable

However, I am getting the error Subscript 'i' is a matrix, it must be of type logical. When I run rlang::lastrace(), I get

 1. ├─df[m2]
 2. ├─dplyr:::`[.grouped_df`(...)
 3. ├─base::NextMethod()
 4. └─tibble:::`[.tbl_df`(...)
 5.   └─tibble:::tbl_subset_matrix(x, j, j_arg)
 6.     └─tibble:::matrix_to_cells(j, x, j_arg)
 7.       └─rlang::cnd_signal(error_subset_matrix_must_be_logical(j_arg))

My m2 is defined as

m2 <- cbind(seq_len(nrow(df)), as.integer(max.col(!is.na(df[,c(3:28)]), 'first') + 2))

I get the same error whether or not I have the as.integer() function. m2 is a number matrix if I leave the function out.

I think the issue has to do with the dataframe type, but I am not sure. From the referenced post's answer, running

class(TESTL[1,2])
>[1] "integer"

but for my dataframe, running

class(df[1,2])
> [1] "tbl_df"     "tbl"        "data.frame"

EDIT: I've realized the issue is because my data frame is a tibble and not a matrix or data.frame. Once I my tibble data frame to a tibble or matrix, I can perform the matrix index. Is there a reason why?

0 Answers
Related