Getting distance between two words in R

后端 未结 3 1626
我寻月下人不归
我寻月下人不归 2020-12-22 00:59

Say I have a line in a file:

string <- \"thanks so much for your help all along. i\'ll let you know when....\"

I want to return a value

3条回答
  •  感情败类
    2020-12-22 01:38

    Split your string:

    > words <- strsplit(string, '\\s')[[1]]
    

    Build a indices vector:

    > indices <- 1:length(words)
    

    Name indices:

    > names(indices) <- words
    

    Compute distance between words:

    > abs(indices["help"] - indices["know"]) < 6
    FALSE
    

    EDIT In a function

     distance <- function(string, term1, term2) {
        words <- strsplit(string, "\\s")[[1]]
        indices <- 1:length(words)
        names(indices) <- words
        abs(indices[term1] - indices[term2])
     }
    
     distance(string, "help", "know") < 6
    

    EDIT Plus

    There is a great advantage in indexing words, once its done you can work on a lot of statistics on a text.

提交回复
热议问题