I have the following data frame.
df<-data.frame(Id=c(1,1,1,2,2,3,4,4,4,4,5,5),
valor=c("A","A","A","A","B","A","A","A","B","A","A","A"))
df
Id valor
1 1 A
2 1 A
3 1 A
4 2 A
5 2 B
6 3 A
7 4 A
8 4 A
9 4 B
10 4 A
11 5 A
12 5 A
What I want is to create a column where it is assigned by id
, the value of the A
if in the column valor
all are A
, if there is one B
, then what would correspond to all the rows of the id
would be B
.
The expected result is the one shown below.
df
Id valor final
1 1 A A
2 1 A A
3 1 A A
4 2 A B
5 2 B B
6 3 A A
7 4 A B
8 4 A B
9 4 B B
10 4 A B
11 5 A A
12 5 A A
An idea I have is to convert it from long to wide and from there work by columns. I know it would work out, but I would like a solution without having to transform the data. Can you do a group_by()
by id and apply a mutate()
?
How could it be solved?
Something like this occurs to me:
Comments:
Id
where there are valuesB
left_join()
we relate each tableId
is one of those that it hasB
and we completefinal
with that value, if not with the one of the row itself.