Reputation: 2536
I'm trying to run a line of code that reads over 55 columns. 20 of them have distances of the location from other cities. This code looks for the shortest distance and populates a new column with the name of the city that has the shortest distance from the location. I'm running the code on two nearly identical datasets, except the first one has many more columns than the second.
Enrollment_Report$nearest_hub <- hub_locations_list$hub_loc[apply(Enrollment_Report[grep("^dist", names(Enrollment_Report))], 1, which.min)]
It yields this error, but only with the first dataset:
invalid subscript type 'list'
The issue is that this code works with one data set and not another. The code has no typos, and with the first dataset, it the class looks like:
class(Enrollment_Report)
[1] "tbl_df" "tbl" "data.frame"
But the second dataset, that the code works on, is this class:
class(all_employee_locations)
[1] "spec_tbl_df" "tbl_df" "tbl" "data.frame"
My question: how do I get the first dataset to be class spec_tbl_df? I don't know why R reads in the second dataset automatically this way, and I can't find any function to make it read it in this way.
It's important that I make this class explicit because this code went from working to suddenly not working (even after resetting my session).
Upvotes: 0
Views: 3981
Reputation: 2536
Final Update, this ended up working:
It did not matter if it was class spec_tbl_df. One row of my tibble had lots of NAs. For some reason, R got confused and thought that the tibble was a list (even though, again, class(dataset) yielded tbl). Removing the row of mostly NAs allowed the code to work.
For future reference, if you DO need your dataset to be class spec_tbl_df, then @Akrun was correct that this is a byproduct of readr vs readxl. read_csv reads in the datasets as spec_tbl_df, and read_excel just reads them in as tibbles.
For some reason, if you need it to be class spec_tbl_df, my workaround was to read the file in as a Excel file, write it as a csv, and then to read it back in with read_csv. This made it class spec_tbl_df.
Upvotes: 1