I am trying to create new fields from a df based on if the conditions match. Below is the df I am trying to use.
abc<- tibble::tribble(
~type, ~match_type, ~count,
"type b", "alpha", 2,
"type a", "alpha", 4,
"type b", "alpha", 1,
"type a", "alpha", 2,
"type a", "beta", 32,
"type a", "beta", 40,
"type a", "beta", 39,
"type a", "beta", 40,
"type a", "beta", 55,
"type b", "beta", 66,
"type b", "beta", 35,
"type b", "beta", 72,
"type b", "beta", 54,
"type b", "beta", 30,
"type b", "beta", 22,
"type b", "beta", 24,
"type b", "beta", 13,
"type b", "beta", 32,
"type b", "beta", 18,
"type b", "beta", 40
)
Now if match_type
is alpha
then create a new field called alpha and sum up the count numbers there and similar for beta.
This is what I have tried so far and the error which I get.
abc %>% mutate(alpha=(count[match_type =="alpha"]),
beta=(count[match_type =="beta"]))
Error: `mutate()` argument `alpha` must be recyclable.
ℹ `alpha` is `(count[match_type == "alpha"])`.
x `alpha` can't be recycled to size 20.
ℹ `alpha` must be size 20 or 1, not 4.
I am trying to create a new df like this (the numbers might not add up in this example)
result <- tibble::tribble(
~type, ~alpha, ~beta,
"type b", 22, 2,
"type a", 12, 4
)
Once I get this above df I want to insert those values in this dataframe based on the field type
which as of now are na
.
final_df <-tibble::tribble(
~type, ~alpha, ~beta, val1 ,val2,
"type b", na, na, 4,5,
"type a", na, na,3,2,
"type c", 22, 2,2,3,
"type d", 12, 4,12,12,
"type e", 22, 2,4,5,
"type f", 12, 4,3,4
)
Am I doing too many steps. is there a simple way to do it.Thank you