I have a data frame with four columns. I would like to create a new column where the value depends on the other column row above. For example, I have a data set like this:
| Day | Precipitation | Condition |
|---|---|---|
| 1 | 3 | Wet |
| 2 | 0 | Dry |
| 3 | 3 | Wet |
I would like the final product to look something like this?
| Day | Precipitation | Condition | Day Before |
|---|---|---|---|
| 1 | 3 | Wet | |
| 2 | 0 | Dry | Wet |
| 3 | 3 | Wet | Dry |
Any ideas on how I can do this?
CodePudding user response:
You may try
library(dplyr)
df %>%
mutate('Day Before' = lag(Condition))
Day Precipitation Condition Day Before
1 1 3 Wet <NA>
2 2 2 Dry Wet
3 3 3 Wet Dry
CodePudding user response:
Plain R approach:
To define the Day Before column , add NA to the beginning of the Condition column (df$Condition) and remove the last element in that vector (df$condition[-length(df$condition)).
df$DayBefore <- c(NA,df$Condition[-length(df$Condition)])
df
Day Percepitation Condition DayBefore
1 1 3 wet <NA>
2 2 0 dry wet
3 3 3 wet dry
