Replace entire expression that contains a specific string

后端 未结 2 1085
花落未央
花落未央 2021-01-03 13:06

I have data frame that has a column with large number of file names like:

d <- c(\"harry11_scott80_norm.avi\",\"harry11_norm.avi\",\"harry11_scott80_lpf.         


        
相关标签:
2条回答
  • 2021-01-03 13:10

    Here's one way

    > gsub(".*_scott80_.*", "incongruent", d)
    [1] "incongruent"           "harry11_norm.avi"      "incongruent"          
    [4] "joel51_lpf.avi"        "rich82_joel51_lpf.avi"
    

    Or with grep

    > d[grep("_scott80_", d)] <- "incongruent"
    > d
    [1] "incongruent"           "harry11_norm.avi"      "incongruent"          
    [4] "joel51_lpf.avi"        "rich82_joel51_lpf.avi"
    

    To address your edit, I believe this will do it (using | to mean "or")

    gsub(".*(_scott80_|_harry11_).*", "incongruent", d)
    

    Of course, you don't have any strings in d that match "_harry11_"

    0 讨论(0)
  • 2021-01-03 13:13

    If your filenames are all of the same format, that is those with two names i.e harry11_scott80_norm.avi always have two underscores, and those with one name i.e. harry11_norm.avi always have one underscore, you can quickly use something like this to rename your files:

    d = gsub(".*_.*_.*", "incongruent", d)
    > d
    [1] "incongruent"      "harry11_norm.avi" "incongruent"      "joel51_lpf.avi"  
    [5] "incongruent"
    
    d =gsub(".*_.*","congruent",d)
    > d
    [1] "incongruent" "congruent"   "incongruent" "congruent"   "incongruent"
    
    0 讨论(0)
提交回复
热议问题