Filling in a data frame with three different values

Viewed 38

So I am working on a project utilizing nested-loops, as this is the preferred method. I have attached a desired (condensed) output for the final data frame below.

    1   2   3   4   5   6   7
1   a   NA  c   NA  e   NA  g
2   NA  1   NA  3   NA  5   NA
3   a   NA  c   NA  e   NA  g
4   NA  1   NA  3   NA  5   NA
5   a   NA  c   NA  e   NA  g
6   NA  1   NA  3   NA  5   NA
7   a   NA  c   NA  e   NA  g
8   NA  1   NA  3   NA  5   NA
9   a   NA  c   NA  e   NA  g
10  NA  1   NA  3   NA  5   NA
11  a   NA  c   NA  e   NA  g
12  NA  1   NA  3   NA  5   NA
13  a   NA  c   NA  e   NA  g
14  NA  1   NA  3   NA  5   NA
15  a   NA  c   NA  e   NA  g
16  NA  1   NA  3   NA  5   NA

I've got the letters into the frame with alternating rows, but I'm stumped on how to use the code to get the numbers and the NAs into the frame and for my desired output. Here is what I have.

Project = matrix(nrow=100, ncol=26)
for (i in 1:nrow(Project)) {
  if (i %% 2 == 1) {
    Project[i, ] <- letters
  } 
}  

I need to now insert those numbers and get my desired output, but I have zero knowledge of what code to proceed with. To remind, this MUST BE DONE WITH NESTED LOOPS.

1 Answers

Either you define your matrix with the NAs already in place:

# letters to fill, where every even index is NA
fill_letters <- letters
fill_letters[seq(2, 26, by = 2)] <- NA

# numbers to fill, where every even index is NA
fill_numbers <- 0:25
fill_numbers[seq(1, 25, by = 2)] <- NA

matrix(
  data = c(fill_letters, fill_numbers), 
  nrow = 100, 
  ncol = 26, 
  byrow = TRUE
)

Or you have the filled matrix given and you put the NAs via an index matrix into place:

mat_result <- matrix(
  data = c(letters, 0:25), 
  nrow = 100, 
  ncol = 26, 
  byrow = TRUE
) 

mat_index <- matrix(
  data = c(rep_len(c(FALSE, TRUE), length.out = ncol(mat_result)), 
           rep_len(c(TRUE, FALSE), length.out = ncol(mat_result))),
  nrow = 100,
  ncol = 26,
  byrow = TRUE
)

mat_result[mat_index] <- NA
Related