Anand
Anand

Reputation: 109

R - Find index of element from one dataframe and place in another

Folks, I have 2 data frames as follows.

df1 Sorted in reverse order showing the number of times an activity has taken place.
Activity  # of Occurrences
Walking  38
Jogging  26
Running 12

df2 Shows the calories burned doing the activity, again sorted in reverse order of Calories Burned.
Activity  Calories Burned
Running  38
Walking  27
Jogging  12

I would like to add a second column on df2, showing the row index of the Activity from df1. So for example, Running is in Row 3 df1 (row-wise) but it's in Row 1 in df2. Hence is there a way for me to add a second column showing the row indices from df1 as below ?

df2 updated: (or df3)
Activity  Calories Burned  Occurrence Index
Running  38        3
Walking  27        1
Jogging  12        2

All the data comes from one underlying table df0, where each incidence of Activity is recorded as a separate row. I summarise it into df1 & df2 but unsure how to go about the last step. Thanks !

Upvotes: 1

Views: 2800

Answers (2)

Dale Kube
Dale Kube

Reputation: 1460

You can assign the indexes in df1 to a new colum "Index". Then, you can lookup the values by Activity name using the merge() function.

df1$df1_Index <- as.numeric(row.names(df1))
df2 <- merge(df2,df1[c("Activity","df1_Index")],by="Activity")

Upvotes: 1

akrun
akrun

Reputation: 887901

We can use match to create the new column

df1$OccurrenceIndex <-  match(df2$Activity, df1$Activity)
df1
#  Activity NoOfOccurrences OccurrenceIndex
#1  Walking              38               3
#2  Jogging              26               1
#3  Running              12               2

Upvotes: 2

Related Questions