简体   繁体   中英

Populate table column by relative row values of another column in R

I'm trying to populate a table column by relative row values of another column in R . I have a table with two data columns (Col1, Col2) and two point value columns (P1, P2). Data1 is populated, Data2 is not. I want the value of Data2 to be populated by the value in either P1 or P2, based on the relative value of Data 1. In a given row, if the previous value of Data1 is higher than its current value, the Data2 cell is populated by the value in P1. If the previous value of Data1 is lower than its current value, the Data2 cell is populated by the value in P2. To illustrate what I'm trying to do, I've provided two sample tables. The first table is what I have (Data2 is not populated), and the second table is the desired outcome.

Table1 (What I have)

+-----+----+----+-------+-------+
| FID | P1 | P2 | Data1 | Data2 |
+-----+----+----+-------+-------+
|   1 | A  | B  |    50 |       |
|   2 | C  | D  |    40 |       |
|   3 | E  | F  |    60 |       |
|   4 | G  | H  |    70 |       |
|   5 | I  | J  |    65 |       |

Table2 (Desired Outcome)

+-----+----+----+-------+-------+
| FID | P1 | P2 | Data1 | Data2 |  
+-----+----+----+-------+-------+
|   1 | A  | B  |    50 | NA    |  
|   2 | C  | D  |    40 | C     |  
|   3 | E  | F  |    60 | F     |  
|   4 | G  | H  |    70 | H     |  
|   5 | I  | J  |    65 | I     |  
+-----+----+----+-------+-------+

Is there a built in function in R to accomplish this? If not, any advice on how to create one?

A solution using dplyr could be:

df %>%
 mutate(Data2 = ifelse(lag(Data1) > Data1, paste0(P1), paste0(P2)))

  FID P1 P2 Data1 Data2
1   1  A  B    50  <NA>
2   2  C  D    40     C
3   3  E  F    60     F
4   4  G  H    70     H
5   5  I  J    65     I

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM