This is my first question here. I am doing my best to keep it reproduceable. I can´t find any question which solve this issue.
Sample Data
library(dplyr)
Data <- data.frame(
a = sample(1:10),
b = sample(c("T", "F"), 10, replace = TRUE),
c = sample(1:10),
x_a = sample(c("T", "F"), 10, replace = TRUE),
x_b = sample(c("T", "F"), 10, replace = TRUE),
y_a = sample(1:10),
y_b = sample(1:10)
)
Data Print
a b c x_a x_b y_a y_b
1 3 T 3 F T 10 8
2 5 F 7 T F 8 9
3 2 T 9 F T 6 4
4 8 F 5 T F 4 7
5 6 F 6 T F 5 1
6 9 F 2 T F 1 10
7 4 F 8 T F 7 5
8 7 F 1 T T 2 2
9 10 F 10 T F 3 3
10 1 F 4 F T 9 6
Here is what I want to do. I want to create a new column combinded from the following logic.
Data %>% mutate(new = ifelse(starts_with("x") & . == T,rowMeans(starts_with("y")),a))
In words: Take cols with a pattern in its names(starts_with("x"). If one (minimum) value in each observation is True, take the rowmean from cols named with another pattern (starts_with("y")). Else (if only False values are in each row), take the value from col a.
Tried multiple approaches with zero success.i spent the whole morning with solving the problem... Any ideas? Thank you in advance
Aucun commentaire:
Enregistrer un commentaire