0

i need to create an empty data.table, with a variable length. For example, i will be given that n = 2 amd m = 12, then i want the table to have columns such as:

name, ID, nickname, start_1, start_2, count_1, count_2, value_<n>_month_<m>

(value_<n>_month_<m> is repeated m x n times)

i get columns: name, ID, nickname, start_1, start_2, start_3 count_1, count_2, count_3 by using the following code:

  VarStart <- setnames(setDF(lapply(integer(K), function(...) character(0L))),
                               paste0("start", 1:K))
   NewTable <- cbind(NewTable, VarStart)
  VarCount <- setnames(setDF(lapply(integer(K), function(...) character(0L))),
                               paste0("start", 1:K))
   NewTable <- cbind(NewTable, VarCount)

borrowed from here.

But how can i crete columns for variables with both n and m in the column name?

Is there a nicer way to what i already have?

Nneka
  • 1,764
  • 2
  • 15
  • 39

1 Answers1

1

You can use :

n = 2
m = 12

const_col <- c('name', 'ID', 'nickname')
sc_cols <- c(t(outer(c('start', 'count'), seq_len(n),paste0)))
vm_cols <- c(t(outer(seq_len(n), seq_len(m), function(x, y) 
                  sprintf('value_%d_month_%d', x, y))))
all_cols <- c(const_col, sc_cols, vm_cols)

NewTable <- data.table::data.table(matrix(ncol = length(all_cols), 
                         dimnames = list(NULL, all_cols)))

Specify nrow as 0 if you want an empty data.table with 0 rows.

names(NewTable)
# [1] "name"             "ID"               "nickname"        
# [4] "start1"           "start2"           "count1"          
# [7] "count2"           "value_1_month_1"  "value_1_month_2" 
#[10] "value_1_month_3"  "value_1_month_4"  "value_1_month_5" 
#[13] "value_1_month_6"  "value_1_month_7"  "value_1_month_8" 
#[16] "value_1_month_9"  "value_1_month_10" "value_1_month_11"
#[19] "value_1_month_12" "value_2_month_1"  "value_2_month_2" 
#[22] "value_2_month_3"  "value_2_month_4"  "value_2_month_5" 
#[25] "value_2_month_6"  "value_2_month_7"  "value_2_month_8" 
#[28] "value_2_month_9"  "value_2_month_10" "value_2_month_11"
#[31] "value_2_month_12"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • i get an table with one row (all NA), and all columns are of class logi – Nneka May 19 '20 at 07:26
  • Yes, so what do you expect as output then? – Ronak Shah May 19 '20 at 07:34
  • i am just surprised, i guess i expected empty character strings for some reason. Is there a reason why they are logi? like a default setting? – Nneka May 19 '20 at 08:09
  • 1
    Well, we have not initialized any value in matrix which gives by default `NA` value and `class(NA)` is logical. You can have any values that you want, For example to get empty string values, you can do : `data.table::data.table(matrix('', ncol = length(all_cols), dimnames = list(NULL, all_cols)))` , replace `''` with `NA_integer_` or `NA_character_` to get integer and character columns. – Ronak Shah May 19 '20 at 08:15