Question 1) Let's say I have longitudinal data for 4 participants over 4 years i.e. years 0,1,3,4. My goal is to
- check if the data has outcome variables (n1) recorded for at least any 2 timepoints.
- If only one recording is present then delete; otherwise keep it.
- repeat 1) & 2) for multiple outcome variables (m1)
data I have
ID visit n1 m1
1 0 5.6 0
1 1 1.5 NA
1 3 0.5 NA
1 4 NA NA
2 0 6 1
2 1 NA 0
2 3 NA 0
2 4 NA 0
3 0 3.4 0
3 1 2.4 0
3 3 2.5 0
3 4 1 1
4 0 NA NA
4 1 NA NA
4 3 NA NA
4 4 3.3 0
this is what I want
data 1
ID visit n1
1 0 5.6
1 1 1.5
1 3 0.5
1 4 NA
3 0 3.4
3 1 2.4
3 3 2.5
3 4 1
data2
ID visit m1
2 0 1
2 1 0
2 3 0
2 4 0
3 0 0
3 1 0
3 3 0
3 4 1
or this form where we create new variable n12 (0= <2 values present for n1 Vs. 1= >=2 values present for n1) & similarly m12. Later I can delete rows based on the values of these new variables n12 & m12.
ID visit n1 m1 n12 m12
1 0 5.6 0 1 0
1 1 1.5 NA 1 0
1 3 0.5 NA 1 0
1 4 NA NA 1 0
2 0 6 1 0 1
2 1 NA 0 0 1
2 3 NA 0 0 1
2 4 NA 0 0 1
3 0 3.4 0 1 1
3 1 2.4 0 1 1
3 3 2.5 0 1 1
3 4 1 1 1 1
4 0 NA NA 0 0
4 1 NA NA 0 0
4 3 NA NA 0 0
4 4 3.3 0 0 0
I tried Deleting incomplete cases across multiple rows in R studio but the following code gives me '0' observations in mydata as it will delete rows even if single NA is found across rows
mydata = mydata[!mydata$ID %in% mydata[!complete.cases(mydata) ,]$ID, ]
library(plyr)
# counts all the IDs
cnt = count(mydata, "ID")
# Eliminates any ID that doesn't have 2 observations
mydata[mydata$ID %in% cnt[cnt$freq == 2, ]$ID, ]
I also tried the long to wide format this did not work as I guess value in my case are multiple variables
library(dplyr)
mydata <- mydata %>%
tidyr::spread(key=time, value=value) %>% # reformat to wide
na.omit() %>% # delete cases with missingness on any variable (i.e. any time point)
tidyr::gather(key="time", value="value", -ID) # put it back in long format
New Question 2): how should I code if I want to have only rows with visit =0 value of n1 and at least one other visit (1/3/4) recording for n1? to get data like this:
ID visit n1
1 0 5.6
1 1 1.5
1 3 0.5
1 4 NA
3 0 3.4
3 1 2.4
3 3 2.5
3 4 1
Kindly suggest R syntax or method to achieve goals Thanks!