2014-12-13 44 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') 
相關問題