如何删除具有特殊字符的行?

时间:2017-08-11 12:00:23

标签: r regex dataframe grepl

我想删除包含左括号的行“(”来自我的数据框。

我尝试了以下内容:

<script src="https://cdn.datatables.net/1.10.15/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.3.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.3.1/js/buttons.flash.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
<script src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.27/build/pdfmake.min.js"></script>
<script src="https://cdn.rawgit.com/bpampuch/pdfmake/0.1.27/build/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/1.3.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/1.3.1/js/buttons.print.min.js"></script>

<script>
    $(document).ready(function () {


         $('#example').DataTable( {
        dom: 'Bfrtip',
        buttons: [
            'excel'
        ]
    } );


    });
</script>

但这不会追踪df[!grepl("(", df$Name),] 标志

1 个答案:

答案 0 :(得分:6)

您必须使用(双重转义\\

x <- c("asdf", "asdf", "df", "(as")

x[!grepl("\\(", x)]
# [1] "asdf" "asdf" "df"  

只需将其应用于您的df,例如df[!grepl("\\(", df$Name), ]

您还可以考虑使用正则表达式删除所有标点字符:

x[!grepl("[[:punct:]]", x)]

正如@CSquare在评论中指出的那样,here is a great summary about special characters in R regex

评论中的其他意见:
@Sotos:使用pattern='('fixed = TRUE获得性能,因为可以绕过正则表达式。

x[!grepl('(', x, fixed = TRUE)]