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

问题描述 投票:0回答:1

这个问题在这里已有答案:

我有下面提到的数据帧:

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\_"

Dput:

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
))
r dataframe dplyr tidyverse
1个回答
1
投票

因为你有双反斜杠你需要逃避它两次。有了gsub,我们可以做到

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

#[1] "2019-04-01"  "Abc"  "xyz" "Ma_New" "AR_Old" "ST_New"  "RR_New_List"
© www.soinside.com 2019 - 2024. All rights reserved.