1

I was wondering how if I could make 7 other data.frames out of dat1 using lapply such that at each round from left to right each pair of 1s in C1 and C2 become 0 except the last two elements of C1 and C2? (see desired output below)

dat1 <- data.frame(C1 = c(1, 1, 1, 1, 1, 1, 1, 1, 0, 0),
                   C2 = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1))

dat2 <- data.frame(C1 = c(0, 1, 1, 1, 1, 1, 1, 1, 0, 0),
                   C2 = c(0, 1, 1, 1, 1, 1, 1, 1, 1, 1))

dat3 <- data.frame(C1 = c(0, 0, 1, 1, 1, 1, 1, 1, 0, 0),
                   C2 = c(0, 0, 1, 1, 1, 1, 1, 1, 1, 1))

dat4 <- data.frame(C1 = c(0, 0, 0, 1, 1, 1, 1, 1, 0, 0),
                   C2 = c(0, 0, 0, 1, 1, 1, 1, 1, 1, 1))
.
.
.
dat8 <- data.frame(C1 = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),  # the last desired data.frame
                   C2 = c(0, 0, 0, 0, 0, 0, 0, 0, 1, 1))

1 Answer 1

3

We can use lapply by looping over sequence of numbers (1:7), create a two column matrix with the corresponding replicate of rows and rbind with the subset of original data with the same number of rows removed the top

lst1 <- lapply(1:7, function(i) rbind(matrix(rep(c(0, 0), i), ncol = 2,
      dimnames = list(NULL, c("C1", "C2"))), dat1[-seq_len(i), ]))
names(lst1) <- paste0("dat", seq_along(lst1) + 1)

It can be made shorter by using cbind

lapply(1:7, function(i) {n <- rep(0, i)
       rbind(cbind(C1 = n, C2 = n),  dat1[-seq_len(i), ])})

Or it can be also (inspired from @Markus comments)

lapply(0:8, function(i) dat1 * rep(c(0, 1), c(i, nrow(dat1)-i)))

If it needs to be separate objects, use list2env (not recommended though)

list2env(lst1, .GlobalEnv)
Sign up to request clarification or add additional context in comments.

1 Comment

Good catch @rnorouzian. Try lapply(0:8, function(x) {dat1[0:x, ] <- 0; dat1 })

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.