I have three categorical variables i.e. stroke, MI and BP with values of 0 = yes and 1= No. I want to merge them to make a new variable "cvd" out of these three variables where each row with 0 gets 0 values in new cardiovascular variable. For example:
Stroke MI BP CVD
0 1 1 0
1 1 1 1
1 1 0 0
I tried the following code but this is not what i want
transform(koratest, cvd=paste(stroke,MI, BP))
Can someone please help what could be the script for this?
Best,
Thank you for all the solutions. What to do if there is missing values in any of the values to be merged. I want missing values to be labelled as 1 but if there is 0 with missing value, i want cvd variable to have value of 1. For example:
Stroke MI BP CVD
0 1 1 0
1 NA NA 1
0 NA 1 0
How could i achieve such output?
Try,
(rowSums(df) == ncol(df)) * 1
#[1] 0 1 0
Another way:
library(dplyr)
df <- data.frame(Stroke = c(0,1,1),
MI = c(1,1,1),
BP = c(1,1,0))
df %>%
rowwise() %>%
mutate(
CVD = min(Stroke, MI, BP)
) %>%
ungroup()
#> # A tibble: 3 × 4
#> Stroke MI BP CVD
#> <dbl> <dbl> <dbl> <dbl>
#> 1 0 1 1 0
#> 2 1 1 1 1
#> 3 1 1 0 0
Created on 2022-07-11 by the reprex package (v2.0.1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With