Find string in data.frame

后端 未结 4 1677
清歌不尽
清歌不尽 2021-01-05 01:12

How do I search for a string in a data.frame? As a minimal example, how do I find the locations (columns and rows) of \'horse\' in this data.frame?



        
4条回答
  •  鱼传尺愫
    2021-01-05 01:33

    Another way around:

    l <- sapply(colnames(df), function(x) grep("horse", df[,x]))
    
    $animal
    [1] 2 3
    
    $level
    [1] 5
    
    $length
    [1] 4
    

    If you want the output to be matrix:

    sapply(l,'[',1:max(lengths(l)))
    
         animal level length
    [1,]      2     5      4
    [2,]      3    NA     NA
    

提交回复
热议问题