dat1 below contain three variables. There are three unique IDs and each has multible records.
ID <- c(rep(1,7), rep(2,6), rep(3,5))
t <- c(seq(1,7), seq(1,6), seq(1,5))
y <- c(rep(6,7), rep(1,6), rep(6,5))
z <- c(6,NA,NA,NA,NA,NA,NA,1,NA,NA,NA,NA,NA,6,NA,NA,NA,NA)
randn <- rnorm(18,0,1)
dat1 <- data.frame(ID, t, y, z, randn)
Notice that for each ID the value of z is non-missing when t is minimum (the first row for each ID).
I need to create a new column called NewX. Note that each cell in the data frame can be expressed as Cell(i,j), where i is the number of ID and j is the number of record. For example, z(1,1) = 6; z(2,1) = 1, and so on.
Case 1: if j = 1 (i.e., the first record for each ID):
NewX(i,1) = rnorm(n=1, mean = z(i,1)*randn(i,1), sd=1)
Case 2: if j > 1 (i.e., not first record for each ID)
NewX(i,j) = rnorm(n=1, mean = randn(i,j)*z(i,j), sd=1), where z(i,j) = z(i,j-1) - NewX(i,j-1)
NewXis a column, how could it have rows and columns? Did you mean it's a new table?i,s and instead think within each ID... Also, in OP's example,jandtare equivalent.