我有以下设置,我想剪切文本字符串,生成一个列表,然后重新分配回data.table作为嵌套列。它适用于n> 1行,但如果n = 1行则不行。我该怎么做才能确保一致性:
library(data.table)
cutdash <- function(x) {strsplit(x, '-')}
## n > 1 row
x <- data.frame(
text = c("I paid for books-He was not interesting in his teaching.", 'good'),
id = 1:2, stringsAsFactors = FALSE)
## n = 1 row
y <- data.frame(text = "I paid for books-He was not interesting in his teaching.",
id = 3, stringsAsFactors = FALSE)
## good
x2 <- data.table::data.table(x)
x2[, text := cutdash(text)][]
## text id
## 1: I paid for books,He was not interesting in his teaching. 1
## 2: good 2
## bad
y2 <- data.table::data.table(y)
y2[, text := cutdash(text)][]
## text id
## 1: I paid for books 3
## Warning message:
## In `[.data.table`(y2, , `:=`(text, cutdash(text))) :
## Supplied 2 items to be assigned to 1 items of column 'text' (1 unused)
不是第一个只有1行的数据帧只允许重新分配第一个元素。
答案 0 :(得分:2)
您需要使用str_split
或list
将您的号召打包到.
(作为data.table [
内的列表别名。就像这样:
y2[, text := .(cutdash(text))][]
或
y2[, text := list(cutdash(text))][]