Skip to content

"Can't assign to column" error when converting factor columns to lists. #936

@richierocks

Description

@richierocks

Converting a character column to a list works as expected:

DT <- data.table(
  x = c("a", "b c", "d e f")
)
DT[, x := strsplit(x, " ")]

I thought that converting a factor would behave in the same way, but it throws an error:

DT <- data.table(
  x = factor(c("a", "b c", "d e f"))
)
DT[, x := strsplit(as.character(x), " ")]
## Error in `[.data.table`(DT, , `:=`(x, strsplit(as.character(x), " "))) : 
##   Can't assign to column 'x' (type 'factor') a value of type 'list' (not character, factor, integer or numeric)

Assigning to a different column name works OK:

DT[, y := strsplit(as.character(x), " ")]

A workaround is possible using a two-stage conversion:

DT[, x := as.character(x)]
DT[, x := strsplit(x, " ")]

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions