【发布时间】:2019-01-20 14:01:06
【问题描述】:
我有一个包含两列的数据框:
df = data.frame(animals = c("cat; dog; bird", "dog; bird", "bird"), sentences = c("the cat is brown; the dog is barking; the bird is green and blue","the dog is black; the bird is yellow and blue", "the bird is blue"), stringsAsFactors = F)
我需要整个“句子”列中每一行所有“动物”出现的总和。
例如:“animals”第一行 c("cat;dog;bird") = sum_occurrences_sentences_column (cat = 1) + (dog = 2) + (bird = 3) = 6 。
结果将是这样的第三列:
df <- cbind( sum_accurrences_sentences_column = c("6", "5", "3"), df)
我尝试了以下代码,但它们不起作用。
df[str_split(df$animals, ";") %in% df$sentences, ]
str_count(df$sentences, str_split(df$animals, ";"))
任何帮助将不胜感激:)
【问题讨论】: