I'm working with a data frame where the color of an object (red or green) was recorded in ordinal classes corresponding to percent coverage.
I am looking to replace all the classes with their corresponding numerical value, which are stored in a second data frame. What is the most efficient way to go about that?
Example data:
df1 <- data.frame(
object = c("A", "B", "C"),
red = c(1, 0 ,2),
green = c(3, 4, 2)
)
df2 <- data.frame(
ordinal = c(0, 1, 2, 3, 4),
percent = c(0, 25, 50, 75, 100)
)
> print(df1)
object red green
1 A 1 3
2 B 0 4
3 C 2 2
> print(df2)
ordinal percent
1 0 0
2 1 25
3 2 50
4 3 75
5 4 100
Desired outcome:
object red green
1 A 25 75
2 B 0 100
3 C 50 50
My dataset is too large to do this manually, and the actual ordinal classes are not evenly spaced, so I can't just use math to get the numbers.
I have tried using case_when(), but I keep getting an error:
df1 <- df1 %>%
+ case_when(df1[,2:3] == df2$class, df2$percent)
Error in `case_when()`:
! Case 1 (`.`) must be a two-sided formula, not a object.
For what it's worth, I am still relatively new to R.