Logical comparison of elements from named list vs named vector in R

Viewed 73

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!

1 Answers

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

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