当只有一行时,data.table将列表添加为列 [英] data.table add list as column when only one row
问题描述
我具有使用 data.table 对单词进行运算的功能,该功能将矢量列表分配为一列。除非data.table为一行,否则此方法效果很好。我在下面演示这个问题。如何使data.table以将一个向量的列表作为一列分配两个向量的列表,以相同的方式将一个向量的列表分配为一列?
I have function that operates on words using data.table which assigns a list of vectors as a column. This works well unless the data.table is one row. I demonstrate this problem below. How can I make data.table assign the list of one vector as a column in the same way I had it ad a list of 2 vectors as a column?
MWE
dat2 <- dat <- data.frame(
x = 1:2,
y = c('dog', 'cats'),
stringsAsFactors = FALSE
)
library(data.table)
setDT(dat) # 2 row data.table
(dat2 <- dat2[1, ]) # single row data.frame
setDT(dat2)
letterfy <- function(x) strsplit(x, "")
## works as expected when >= 2 rows
dat[, letters := letterfy(y)]
dat
## x y letters
## 1: 1 dog d,o,g
## 2: 2 cats c,a,t,s
## Try on 1 row
dat2[, letters := letterfy(y)]
#Warning message:
#In `[.data.table`(dat2, , `:=`(letters, letterfy(y))) :
# Supplied 3 items to be assigned to 1 items of column 'letters' (2 unused)
# x y letters
#1: 1 dog d
dat2的期望输出
## x y letters
## 1: 1 dog d,o,g
推荐答案
只需将输出包装在 list
中:
> dat2[, letters := list(letterfy(y))][ ]
x y letters
1: 1 dog d,o,g
请注意, dat [,类(字母)]
是列表
;由于通常列表是通过RHS的:=
传递给多个任务的,因此 data.table
似乎有点混乱。我想开发人员有理由在此处取消列出工作清单...但是这种方法也适用于多于一行的情况,即 dat [,字母:= list(letterfy(y)) ]
也可以按预期工作。
Note that dat[ , class(letters)]
is list
; since typically lists are passed on the RHS of :=
for multiple assignments, it seems data.table
was a bit confused. I imagine the developers have a reason for unlisting in the assignment here... but this approach also works when there is more than one row, i.e., dat[ , letters := list(letterfy(y))]
also works as expected.
另一种选择是将字母列分配为字符
通过更改 letterfy
:
Another option is to assign the letters column as a character
vector by changing letterfy
:
letterfy2 <- function(x) lapply(strsplit(x, ""), paste0, collapse = ",")
> dat[ , letters := letterfy2(y)][ ]
x y letters
1: 1 dog d,o,g
2: 2 cats c,a,t,s
dat2[, letters := letterfy2(y)][ ]
x y letters
1: 1 dog d,o,g
这篇关于当只有一行时,data.table将列表添加为列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!