我一直在研究R中的一个函数,并希望返回一个data.frame。但是,当我运行时,它返回0行/ 0列。我确实添加了" print"在if语句中,这是有效的,所以我知道它在循环和if语句中按预期执行。
这是功能:
predict.next.word <- function(word, ng_matrix){
if(ncol(ng_matrix)==3){
for (i in 1:100){
ngram_df <- data.frame()
first_word <- ng_matrix[,1][i]
second_word <- ng_matrix[,2][i]
count_word <- ng_matrix[,3][i]
if (word[1] == first_word && !is.na(first_word)){
matched_factor <- structure(c(second_word, count_word), .Names = c("predicted", "count"))
matched_df <- as.data.frame(as.list(matched_factor))
ngram_df <- (rbind(ngram_df, matched_df))
ngram_df <- transform(ngram_df, count = as.numeric(count))
print (ngram_df) # this works great, but not intention of function
}
}
return (ngram_df)
}
}
以下是我称之为的示例:
test_bigram_word <- c("a")
predict.next.word(test_bigram_word, bigram_index)
答案 0 :(得分:0)
通过在for循环上方移动数据框的初始化来解决它,如下所示:
predict.next.word <- function(word, ng_matrix){
if(ncol(ng_matrix)==3){
ngram_df <- data.frame()
for (i in 1:100){
first_word <- ng_matrix[,1][i]
second_word <- ng_matrix[,2][i]
count_word <- ng_matrix[,3][i]
if (word[1] == first_word && !is.na(first_word)){
matched_factor <- structure(c(second_word, count_word), .Names = c("predicted", "count"))
matched_df <- as.data.frame(as.list(matched_factor))
ngram_df <- (rbind(ngram_df, matched_df))
ngram_df <- transform(ngram_df, count = as.numeric(count))
print (ngram_df) # this works great, but not intention of function
}
}
return (ngram_df)
}
}