0

I think I need a little help finishing this code.

I have a dataset that looks like this:

df1

>     subj_ids activity_names
1          2              5
2          2              5
3          2              3
4          2              3
5          2              4
6          2              4
7          2              1
8          2              1
9          2              6
10         2              6

I'd like to replace the values of activity names with the following values:

df2

  V1                 V2
1  1            WALKING
2  2   WALKING_UPSTAIRS
3  3 WALKING_DOWNSTAIRS
4  4            SITTING
5  5           STANDING
6  6             LAYING

I want to do this in such a way that if df1$activity_names matches with df2$V1, then the value on df1$activity_names should be changed to the corresponding value on df2$V2. So the resulting dataframe should look like this:

>     subj_ids activity_names
1          2              STANDING
2          2              STANDING
3          2              WALKING_DOWNSTAIRS
4          2              WALKING_DOWNSTAIRS
5          2              SITTING
6          2              SITTING
7          2              WALKING
8          2              WALKING
9          2              LAYING
10         2              LAYING

I've set up the following code to do it:

#index
my_i <- df2$V1
my_j <- df2$V2

#use my_merged_data1_sub as a test

df1$activity_names <- replace(df1$activity_names, 
                                          df1$activity_names == 5, "STANDING")

It works when I just do it once, but when I try to generalize it

df1$activity_names <- replace(df1$activity_names, 
                                          df1$activity_names %in% my_i, my_j)

It doesn't come out right. The order and matching come out wrong.

Can anyone help me figure out what's going wrong? Thanks,

Diego
  • 23
  • 6
  • 2
    `df1$activity_names <- df2$V2[match(df1$activity_names, df2$V1)]` – Ronak Shah Feb 19 '21 at 04:41
  • Thank you. This line of code works. But just out of curiosity, is there a way to do it using replace and if necessary a for loop? – Diego Feb 19 '21 at 05:20

0 Answers0