Bobby Heyer
Bobby Heyer

Reputation: 601

How to match rows from one df with columns in another df in R

Basically I've got 2 tables or Data frames (I think that's the term..?), One of them has the identifier in the Row, the other has it in the Column. Like below

df 1

Id     Location
34    Hunter Region
35    Hunter Region
36    Western Region
37    Western Region
38    Western Region
...

df 2

Date        34   35   36   37   38
15/01/18   1.5  2.4  1.4  1.6  2.2
16/01/18   1.5  2.4  1.4  1.6  2.2
17/01/18   1.5  2.4  1.4  1.6  2.2
...

What I want to do is separate df2 into new tables based on the Region (e.g. one for Hunter Region, and one for Western Region)

Upvotes: 0

Views: 68

Answers (1)

R. Schifini
R. Schifini

Reputation: 9313

To separate dataframe df2 into Hunter and Western Region columns you could do:

create two selectors:

sel_hunter = as.character(df1$Id[df1$Location=="Hunter Region"])
sel_western = as.character(df1$Id[df1$Location=="Western Region"])

add the "Date" column to these selectors:

sel_hunter = c("Date", sel_hunter)
sel_western = c("Date", sel_western)

and then proceed to separate df2 into two dataframes:

df2_hunter = df2[ , sel_hunter]

      Date  34  35
1 15/01/18 1.5 2.4
2 16/01/18 1.5 2.4
3 17/01/18 1.5 2.4


df2_western = df2[ , sel_western]

      Date  36  37  38
1 15/01/18 1.4 1.6 2.2
2 16/01/18 1.4 1.6 2.2
3 17/01/18 1.4 1.6 2.2

Upvotes: 1

Related Questions