Search for multiple values in a column in R

后端 未结 2 1698
小鲜肉
小鲜肉 2021-01-25 20:53

I have a data frame with two columns:

df = data.frame(animals = c(\"cat; dog; bird\", \"dog; bird\", \"bird\"), sentences = c(\"the cat is brown; the dog is bar         


        
2条回答
  •  盖世英雄少女心
    2021-01-25 21:06

    A map() way to manipulate each animal piece in the first column.

    library(tidyverse)
    string <- unlist(str_split(df$sentences, ";"))
    
    df %>% rowwise %>%
      mutate(SUM = str_split(animals, "; ", simplify = T) %>%
        map( ~ str_count(string, .)) %>%
        unlist %>% sum)
    
    #   animals        sentences                                           SUM
    #                                                            
    # 1 cat; dog; bird the cat is brown; the dog is barking; the bird...   6
    # 2 dog; bird      the dog is black; the bird is yellow and blue       5
    # 3 bird           the bird is blue                                    3
    

提交回复
热议问题