I have this dataset
dat=structure(list(A = c("n",
"n", "F", "F"), Par = c(1,
1, 8, 3), var = c(1, 10, 1,5), dat = c("T",
"T", "T", "T")), row.names = c(NA, 4L
), class = "data.frame")
I want to add by the groups in A , i tried this did not work:
dat%>%group_by(A)%>% mutate(ye = c( "40-25", "25-200"))
Error:
! Assigned data value
must be compatible with existing data.
✖ Existing data has 4 rows.
✖ Assigned data has 2 rows.
ℹ Only vectors of size 1 are recycled.
Run rlang::last_error()
to see where the error occurred.
A Par var dat ye
1 n 1 1 T "40-25"
2 n 1 10 T "40-25"
3 F 8 1 T "25-200"
4 F 3 5 T "25-200"
CodePudding user response:
In a simple case like this you can use an ifelse()
or case_when()
. The latter may be preferable as it is easier to add additional values if the logic changes:
dat |>
mutate(
ye = case_when(
A == "n" ~ "40-25",
A == "F" ~ "25-200",
TRUE ~ "A is neither n nor F"
)
)
However, case_when()
can also become unwieldy if you have many conditions.
I prefer to join if you are going to do this with a lot of values, as it allows you to edit the data rather than the logic.
values_to_join <- data.frame(
A = c("n", "F"),
ye = c("40-25", "25-200")
)
left_join(dat, values_to_join, by = "A")
# A Par var dat ye
# 1 n 1 1 T 40-25
# 2 n 1 10 T 40-25
# 3 F 8 1 T 25-200
# 4 F 3 5 T 25-200
CodePudding user response:
Probably you can try summarise_all
unnest
library(dplyr)
library(tidyr)
dat %>%
group_by(A) %>%
summarise_all(list) %>%
mutate(ye = c("40-25", "25-200")) %>%
unnest(cols = c(Par, var, dat))
which gives
A Par var dat ye
<chr> <dbl> <dbl> <chr> <chr>
1 F 8 1 T 40-25
2 F 3 5 T 40-25
3 n 1 1 T 25-200
4 n 1 10 T 25-200
CodePudding user response:
If I understand your goal, you could split by group and add your ye
values sequentially by group:
library(dplyr)
library(purrr)
dat %>%
group_by(A) %>%
group_split() %>%
map2_dfr(
c("40-25", "25-200"),
~ mutate(.x, ye = .y)
)
# A tibble: 4 × 5
A Par var dat ye
<chr> <dbl> <dbl> <chr> <chr>
1 F 8 1 T 40-25
2 F 3 5 T 40-25
3 n 1 1 T 25-200
4 n 1 10 T 25-200
If instead you want to create ye
based on specific values of A
, see @SamR’s answer or use dplyr::recode()
:
dat %>%
mutate(ye = recode(
A,
F = "40-25",
n = "25-200"
))