-2

I'm trying to get a loop to work with a function that prints a list and save the list for each row in a single new column.

I can run the loop, but I end up with only the results list for the last word repeated in every row in the new column.

library(vwr)
test = c("cat", "bat", "rat", "tow", "row")
test = data.frame(test)
for (i in test$test){
    test$save[i] = levenshtein.neighbors(i,test$test)[1]}

Once the loop runs, I end up with test$save as the list of neighbors for "row" ("tow") in every cell.

I want each cell in the test$save column to have the neighbors for that word (i.e. "cat" should have "bat" and "rat"; "tow" should have "row"). Eventually, this will be with 100,000+ words in a dataset with 50 other columns, so I can't do too much manual work either.

Thanks for any help you can offer!

Rachel
  • 11
  • 1
  • 8
  • Please take a look at what you can and should do to give a [minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example); in a nutshell, you should include (1) minimal sample data, (2) reproducible code that we can copy&paste including any non-base R `library` calls (where is `levenshtein.neighbors` from?), and (3) your expected output. – Maurits Evers Jun 28 '19 at 12:57
  • Thank you! I have included more code with where levenshtein.neighbors comes from. I hope this clarifies those issues. – Rachel Jun 28 '19 at 13:19

1 Answers1

0

I am not completely sure what you want to achieve but this code seems to work fine:

library(vwr)

test <- list(cat = c("cat", "bat", "rat", "tow", "row"))

for (i in test$cat){
  test$save[i] = levenshtein.neighbors(i,test$cat)[1]
}
test$save

In this example, test$cat is a vector and not a dataframe. The rest of the code remains unchanged.

eastclintw00d
  • 2,250
  • 1
  • 9
  • 18
  • Oh! Thank you, I think this is very close. I should clarify that I need test$save to be a single column in a larger dataframe, where each row is dedicated to one word and each column is a word feature. I can coerce the "word" column into a list, but I'm not sure how to coerce the results of test$save$cat and test$save$bat, etc. into a single column when I have so many words. Do you have any suggestions? – Rachel Jun 28 '19 at 13:29
  • Technically a dataframe is just a special case of a list, i.e. a list where every element is a vector of the same length. In your case it seems that it would be better to work with lists as the example yields a varying number of neighbors. – eastclintw00d Jun 28 '19 at 22:40