mercredi 27 septembre 2023

generate a pattern dataframe using R

I wish to make a dataframe as below. and I wish to have 3 parameter x,y,z,

x is number of "a" (number of "b" = column number, at first column, number of "b" is 1),

y is number of column,

z is number of row,

if x=2, y=5, z=16, then enter image description here

this is my code, I can't solve this problem. 
1. how to fill the empty space.
2. how to rename the column ([x]to[column number])
I need help.

library(dplyr)


x <- 2
z <- 16
w <- 5

df <- data.frame(matrix("", nrow = z, ncol = w))

for (col in 1:w) {
  a_count <- x
  b_count <- col
  
  df[1:a_count, col] <- "a"
  df[(a_count + 1):(a_count + b_count), col] <- "b"
}

print(df)


  X1 X2 X3 X4 X5
1   a  a  a  a  a
2   a  a  a  a  a
3   b  b  b  b  b
4      b  b  b  b
5         b  b  b
6            b  b
7               b
8                
9                
10               
11               
12               
13               
14               
15               
16              



Aucun commentaire:

Enregistrer un commentaire