2014-12-13 45 views
0

我想用一列名为“ngrams”和“pred”的2列创建一个空的数据框。在数据框中写一个列表作为元素在r

df <- data.frame(nGrams=character(), pred = character(), stringsAsFactors=FALSE) 

我需要“预见”,在列中的每个元件是字的矢量,但如果我初始化“预解码值=列表()”中的数据帧将不添加该列。

我尝试

> pred 
[1] "a" "the" "not" "that" "to" "an" 

df[nrow(df)+1, ] <- c("is", pred) 

Error in matrix(value, n, p) : 
    (converted from warning) data length [7] is not a sub-multiple or multiple of the number of columns [2] 

df[nrow(df)+1, ] <- c("the", list(pred)) 

Error in `[<-.data.frame`(`*tmp*`, nrow(df) + 1, , value = list("the", : 
     (converted from warning) replacement element 2 has 6 rows to replace 1 rows 

任何人都可以告诉我什么是正确的做法吗?提前致谢。

编辑

我使用data.table

dt <- data.table(nGrams = my_ngrams, pred = list_pred) 

其中list_pred是一个列表的列表的解决方案。但是,了解数据框架的正确方法仍然很好。

回答

0

你可以尝试

d1 <- data.frame(nGrams='the', pred=I(list(pred))) 
str(d1) 
#'data.frame': 1 obs. of 2 variables: 
#$ nGrams: Factor w/ 1 level "the": 1 
#$ pred :List of 1 
# ..$ : chr "a" "the" "not" "that" ... 
#..- attr(*, "class")= chr "AsIs" 

或者用空数据框df

df[nrow(df)+1,] <- list('is', list(pred)) 
str(df) 
#'data.frame': 1 obs. of 2 variables: 
#$ nGrams: chr "is" 
#$ pred :List of 1 
# ..$ : chr "a" "the" "not" "that" ... 

其中,

pred <- c('a', 'the', 'not', 'that', 'to', 'an') 
相关问题