Home > Mobile >  R function for repeat value on different lines
R function for repeat value on different lines

Time:03-08

I have a dataframe on which there are several rows for the same individual, I have a value that appears only on the first row and I would like to repeat it on all the rows of the same individual. I work on r and I'm a beginner, so I have no idea how to do it. Here is an example of what I would like :

ID     Status 
1      0
1
1
2      1
2

I would like to repeat all the status 0's on the subject lines 1 and all the status 1's on the subject lines

Thank you in advance for your help

CodePudding user response:

If your data look like this:

df <- data.frame(
    ID  = c(1,1,1,2,2), 
    Status = c(0, NA, NA, 1, NA))

You can pick the value from the first row for each ID.

library(dplyr)
df %>% group_by(ID) %>% 
  mutate(Status = Status[1])


# A tibble: 5 × 2
# Groups:   ID [2]
     ID Status
  <dbl>  <dbl>
1     1      0
2     1      0
3     1      0
4     2      1
5     2      1
> 


CodePudding user response:

ID Status Sexe HEMOGLOBIN 1 1 2 14,8 1 NA NA 12,6 1 NA NA 12,9 1 NA NA 13,3 1 NA NA 13 1 NA NA 12,7 1 NA NA 12,9 1 NA NA 13 1-2 0 1 14,9 1-3 0 1 17,2 1-3 NA NA 16,6 1-3 NA NA 16,7

the data is like this, on the first lines I have the socio-demographic characteristics and on the others I have measurements of haemoglobin levels over different periods @Zhiqiang Wang

  • Related