igorjrr
igorjrr

Reputation: 902

R accessing data by $ in list

I understand I'm probably lacking some basic knowledge. However, could someone please clarify why the same structure works in one code but not in the other?

Data:

> head(Countries)
   LocID NamePrint TreeLevel TypeNameShort IsSmallCountry ParentID
15   1   A         4         Country              0       10
16   2   B         4         Country              0       10
17   3   C         4         Country              0       10
18   4   D         4         Country              0       10
19   5   E         4         Country              0       10
20   6   F         4         Country              0       10

Sequence:

CountryIdx <- 1
Location <- Countries[CountryIdx,,drop=F]
ParentLocation <- subset(Locations, LocID==Location$ParentID)
GrandParentLocation <- subset(Locations, LocID==ParentLocation$ParentID)

> typeof(Location)
[1] "list"

> typeof(ParentLocation)
[1] "list"

> typeof(GrandParentLocation)
[1] "list"

> class(Location)
[1] "data.frame"

> class(ParentLocation)
[1] "data.frame"

> Location
   LocID NamePrint TreeLevel TypeNameShort IsSmallCountry ParentID
15   1   A         4         Country             0        10

> ParentLocation
   LocID NamePrint TreeLevel TypeNameShort IsSmallCountry ParentID
14   10  XF        3         Unknown             0        30

Now the problem:

PropUrbanRuralCountry <- subset(PropUrbanRural, LocID==Location$LocID)

The line abovefails: Error in Location$LocID : $ operator is invalid for atomic vectors

> PropUrbanRuralCountry <- subset(PropUrbanRural, LocID==ParentLocation$LocID)

The line above works

If Location and ParentLocation are both lists, and subset is using the same data, why one fails and the other doesn't?

Ideally, I'd like to always use the $, but I can't figure out why the same type of data (list). I wish R could simplify his.

Upvotes: 0

Views: 45

Answers (1)

igorjrr
igorjrr

Reputation: 902

As pointed out by @MrFlick in the comments, the PropUrbanRural dataset had a column named Location that caused R to refer to that column instead of the separate Location dataset. I renamed the column and now it works. Thank you, @MrFlick.

Upvotes: 1

Related Questions