如何从R中的特定列中删除“ \”符号

时间:2019-04-18 07:53:48

标签: r dataframe dplyr tidyverse

我有以下提到的数据框:

DF

Date          Count
2019-01-01    150
Ma\_New       50
AR\_Old       50
ST\_New       50

无论何时何地,我都需要从第一列中删除“ \”号,并且需要像这样的数据框。

Required_DF

Date          Count
2019-01-01    150
Ma_New        50
AR_Old        50
ST_New        50

我尝试过

Required_DF <- within(DF, sapply(var, function(x) x <- replace(x, x=="Ma\_New", "Ma_New"))),但出现错误Error: '\_' is an unrecognized escape in character string starting ""Ma\_"

投放:

structure(list(Date = structure(c(1L, 18L, 19L, 20L, 21L, 22L, 
23L), .Label = c("2019-04-01", "2019-04-02", "2019-04-03", "2019-04-04", 
"2019-04-05", "2019-04-06", "2019-04-07", "2019-04-08", "2019-04-09", 
"2019-04-10", "2019-04-11", "2019-04-12", "2019-04-13", "2019-04-14", 
"2019-04-15", "2019-04-16", "2019-04-17", "Abc", "xyz", "Ma\\_New", 
"AR\\_Old", "ST\\_New", "RR\\_New\\_List"), class = "factor"), 
    `# of Count` = structure(c(32L, 16L, 55L, 1L, 50L, 58L, 
    1L), .Label = c("  0", "  1", " 10", "100", "102", "103", 
    "109", "115", " 12", " 15", "155", "161", "162", "167", " 17", 
    "172", "175", "188", "189", " 19", "  2", "201", "203", "207", 
    "222", "240", "241", "246", "251", "285", "288", "295", " 30", 
    "305", "307", "321", "334", "339", " 34", "346", "370", "372", 
    " 38", " 43", " 44", "  5", " 50", "507", " 53", " 54", " 55", 
    " 56", " 57", " 58", "  6", " 60", " 61", " 63", " 65", " 74", 
    " 78", " 79", "  9", " 96"), class = "factor")), .Names = c("Date", 
"# of Count"), class = "data.frame", row.names = c(NA, 7L
))

1 个答案:

答案 0 :(得分:1)

如果您有两个反斜杠,则需要将其转义两次。使用gsub,我们可以做到

gsub("\\\\", "", df$Date)

#[1] "2019-04-01"  "Abc"  "xyz" "Ma_New" "AR_Old" "ST_New"  "RR_New_List"