I have this df, and I want to make four new columns:
cuadri
conforme
AQ
n
1
FALSE
2a HTR
1
1
FALSE
3a HMI
1
1
FALSE
PB HTR
1
1
FALSE
Pediatria
1
1
FALSE
PV
4
1
TRUE
2a HTR
8
1
TRUE
3a HMI
9
[...]
2p
FALSE
2a HTR
5
2p
FALSE
3a HMI
7
2p
FALSE
4a HG
7
2p
FALSE
8a HG
4
2p
FALSE
Arritmias
1
2p
FALSE
PB HTR
7
2p
FALSE
Pediatria
4
c1t: If 'cuadri' is 1 AND 'conforme' is true, this cell is the value in 'n'
c1f: If 'cuadri' is 1 AND 'conforme' is false, this cell is the value in 'n'
c2t: If 'cuadri' is 2 AND 'conforme' is true, this cell is the value in 'n'
c2f: If 'cuadri' is 2 AND 'conforme' is false, this cell is the value in 'n'
For example, with AQ=2a HTR,
would have c1f=1, c1t=8, c2f=5 and c2t=8
I tried with mutate and ifelse, but I haven't got it:
AQsum2<-AQsum %>%
mutate(c1t=ifelse(cuadri==1 & conforme==TRUE,AQsum$n,"")) %>%
mutate(c1f=ifelse(cuadri==1 & conforme==FALSE,AQsum$n,"")) %>%
mutate(c2t=ifelse(cuadri=="2p" & conforme==TRUE,AQsum$n,"")) %>%
mutate(c2f=ifelse(cuadri=="2p" & conforme==FALSE,AQsum$n,""))
How I can do it?
Thanks
In R tables all values in a column must be numeric or strings (not mixed).
You don't mention what error you encountered but adapting your solution in the following way, works for me:
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(magrittr)
AQsum <- data.frame(
cuadri = c("1","1", "2p","2p"),
conforme = c(F,T,F,T),
AQ = rep("2a HTR",4),
n = c(1,8,5,8)
)
AQsum %>%
mutate(
c1t = ifelse(cuadri == "1" & conforme == T, n, -999) ,
c1f = ifelse(cuadri == "1" & conforme == F, n, -999) ,
c2t = ifelse(cuadri == "2p" & conforme == T, n, -999) ,
c2f = ifelse(cuadri == "2p" & conforme == F, n, -999)
) %>%
print()
#> cuadri conforme AQ n c1t c1f c2t c2f
#> 1 1 FALSE 2a HTR 1 -999 1 -999 -999
#> 2 1 TRUE 2a HTR 8 8 -999 -999 -999
#> 3 2p FALSE 2a HTR 5 -999 -999 -999 5
#> 4 2p TRUE 2a HTR 8 -999 -999 8 -999
Created on 2022-10-29 with reprex v2.0.2