Abhinav Sood

Subsetting a list with named components in R using dollar notation

The more I work with R, the more it amazes me. This particular post is about accessing a named component of a list using the component name with the dollar notation

> name$component_name

So if you have a list named assets with two named components, rate_depreciation and rate_exchange, then you can select them by using assets$rate_depreciation and assets$rate_exchange respectively.

What is amazing, is that the component names can also be selected by using the first few letters of the component name – with the minimum number of letters needed to identify them uniquely. So, rate_depreciation component can be selected as:

> assets$rate_d

Similarly, rate_exchange component can be selected as:

> assets$rate_e

This partial-match behavior results from the exact attribute being implicitly set to FALSE in R. If you want R to select only those components that match exactly with the specified component name, you can explicitly set exact=TRUE to alter this behavior:

> name[[component_name, exact=TRUE]]

Now, if you searched for rate_exchange with a shortened name as the selector and exact match flag set, you would get a NULL instead of contents of your named component.

> assets[[rate_e, exact=TRUE]]
NULL

Interesting and even nifty, maybe, when you are in a hurry. But, handle with care!

Exit mobile version