Hello! I'm trying to create a table like below with the code (which is supposed to grab the prior time period's and the opposite group's, information). It seems the problem now is that it is complaining about the length of y. I tried various things to try to fix this, but I feel stuck right now.
group<-c("A", "A", "B", "B", "A", "A", "B", "B", "A", "A", "B", "B")
time<-c(1,1,1,1,2,2,2,2,3,3,3,3)
age<-c(2,3,2,3,2,3,2,3,2,3,2,3)
var<-c(2,9,3,0,0,0,3,2,6,3,4,7)
df<-data.frame(cbind(group,time,age,var))
df$newvar<-NA
df <- arrange(df, time, group)
list<-unique(age)
listtime<-unique(time)
df$time <- as.numeric(df$time)
df$y<- df$time-1
df<-df %>% mutate_all(as.character)
a <- min(df$y)
b <- max(df$y)
for (j in 1:length(list)) {
for (x in a:b) {
i<-list[j]
c<-list
a_var<-df$var[df$time==c & df$group == "A" & df$age==i]
b_var<-df$var[df$time==c & df$group == "B" & df$age==i]
df<-df %>% mutate(newvar = ifelse(group== "A" & y==c & age==i, b_var,
ifelse(group=="B" & y==c & age==i, a_var,
NA)))
}
}
I'm trying to get this table:
Any help is appreciated!