用异构类型初始化data.table

alb*_*rto 1 r data.table

我需要建立一个很大的data.table地方,每一行都是用户,而列是不同类型的属性。我需要逐行填写表格。我应该如何初始化它?

例如,如果我这样做:

dt.hetero <- data.table(matrix(-1, nrow=3, ncol=6))
names(dt.hetero) <- c("name", "lastname", "city", "age", "weight", "heigh")
dt.hetero[1, age:=34]
dt.hetero[1, name:="alice"]
Run Code Online (Sandbox Code Playgroud)

它期望在任何地方都翻倍,因此当我尝试输入字符串时收到警告:

Warning messages:
1: In `[.data.table`(dt.hetero, 1, `:=`(name, "alice")) :
  NAs introduced by coercion
2: In `[.data.table`(dt.hetero, 1, `:=`(name, "alice")) :
  Coerced 'character' RHS to 'double' to match the column's type. Either change the target column to 'character' first (by creating a new 'character' vector length 3 (nrows of entire table) and assign that; i.e. 'replace' column), or coerce RHS to 'double' (e.g. 1L, NA_[real|integer]_, as.*, etc) to make your intent clear and for speed. Or, set the column type correctly up front when you create the table and stick to it, please.
dt.hetero[1, name:="alice"]
Run Code Online (Sandbox Code Playgroud)

编辑:

我按顺序获取用户数据。因此,该过程是

对于每个用户:

  • 获取用户数据
  • 将用户数据复制到data.table中的行

返回数据表

小智 5

您可以在创建空的data.table时直接指定各列的类型:

dt.hetero <- data.table(name = character(3L), 
                        lastname = character(3L), 
                        city = character(3L), 
                        age = integer(3L), 
                        weight = double(3L), 
                        height = double(3L))
Run Code Online (Sandbox Code Playgroud)

您可以通过实际需要的行数来更改数字“ 3”。