2

Sorry if this is a duplicate, I read through a number of threads but couldn't really find a good explanation.

I have a dataset (dataframe) where I calculated the mean value of each column. I now want to do some logical comparisons between these values. I used lapply to get the means

means_list <- lapply(dataset_df, mean)

which outputs a named list. But when I try to compare two elements of this list, e.g.

means_list["condition1"] > means_list["condition2"]

I get an error ("comparison of these types is not implemented").

I don't get that error if I use sapply instead so that I'm working with a named vector. I can also get around the error by converting the list to a dataframe with as.data.frame first.

So, I feel like I'm doing something wrong when subsetting a named list here but I don't quite understand how. Is there a correct way to subset the list so that I can do the logical comparison? Or is this not possible with named lists?

Thanks!

Lea W.
  • 23
  • 3
  • Take a look here: https://stackoverflow.com/questions/1169456/the-difference-between-bracket-and-double-bracket-for-accessing-the-el – Martin Gal Aug 19 '21 at 13:22
  • 1
    Thank you, that explains it really well. Kind of tricky that double brackets are only really required for lists. I can already tell that I will probably forget to do this in the future. – Lea W. Aug 19 '21 at 13:28

1 Answers1

1

To access to the element of a list by its name, you have to use double brackets:

means_list[["condition1"]] > means_list[["condition2"]]
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225
  • Thank you so much for the quick reply! I will look up the difference between `[ ]`and `[[ ]]` now! – Lea W. Aug 19 '21 at 13:09