r - 如何将列表分配为数据表中的观察值?

标签 r dataframe data.table

我有一个包含性格观察的数据表:

library(data.table)
library(stringr)

DT = data.table(strings = c('AAABD', 'BBDA', 'AACBDAA', 'ABACD'))

我想创建一个变量,其中包含每个观察值中“A”、“AA”和“AAA”的计数作为列表。为此,我创建了一个函数 foo:

foo <- function(str) {
    n <- str_count(str, 'A')
    n2 <- str_count(str, 'AA')
    n3 <- str_count(str, 'AAA')
    df <- list('n' = n, 'n2' = n2, 'n3' = n3)

    return(df)
}

我将这个函数应用到 DT 以创建一个新的变量用于计数观察作为一个列表:

DT[, count := foo(strings)]

当我这样做时,我收到此错误:

Warning message:
In `[.data.table`(DT, , `:=`(counts, foo(strings))) :
  Supplied 3 items to be assigned to 4 items of column 'counts' (recycled leaving remainder of 1 items).

返回的数据表包含大小为 4 而不是大小 3 的计数变量列表,并且对于变量 strings。如何将列表分配为数据表中的观察值?

最佳答案

您需要转置列表:

foo <- function(str) {
  n <- str_count(str, 'A')
  n2 <- str_count(str, 'AA')
  n3 <- str_count(str, 'AAA')
  df <- transpose(list('n' = n, 'n2' = n2, 'n3' = n3)) # <- add transpose 
  return(df)
}

DT[, count := foo(strings)]
DT
#     strings count
#  1:   AAABD 3,1,1
#  2:    BBDA 1,0,0
#  3: AACBDAA 4,2,0
#  4:   ABACD 2,0,0

str(DT)
# Classes ‘data.table’ and 'data.frame':    4 obs. of  2 variables:
# $ strings: chr  "AAABD" "BBDA" "AACBDAA" "ABACD"
# $ count  :List of 4
#  ..$ : int  3 1 1
#  ..$ : int  1 0 0
#  ..$ : int  4 2 0
#  ..$ : int  2 0 0

关于r - 如何将列表分配为数据表中的观察值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53383344/

相关文章:

r - "sf"包 (R) 是否有一个函数可以完全合并几何图形?

python - 组合多个偶尔重叠的 DataFrame

Python Pandas - 数据框中多列的滚动回归

r - 如何在函数中使用 char 变量来过滤 data.table 中的列?

r - data.table 行引用行为

r - 在geom_sf_text中,如何在美学上微调x和y?

r - 确定重叠范围 - R

python - Pandas 删除所有不是 'datetime' 类型的行

r - 跨多个顺序因素的数据表分组

r - 如何获取所有终端节点 - r 中的权重和响应预测 'ctree'