繁体   English   中英

使用 R 替换某些特殊字符,如 @ 或 - 用它们的实际单词“at”和“dash”

[英]Replacing certain special characters like @ or - with their actual words "at" and "dash" using R

我一直在研究 R 中的一些数据清理程序,但遇到了一个问题。 我试图用它们的字符对应物“at”替换像“@”这样的特殊字符。

我尝试过subgsubsetNames甚至replace . 所有这些都会产生相同的结果:它只是在我的数据中给了我大量的NA 我有一个数据示例,仅供参考。

在此处输入图片说明

想象一下,我看不到所有@ 符号的位置,我想搜索整个数据集并替换所有这些。 我的实际数据集有 50 列,因此按列操作是行不通的。

##################编辑##################

aa <- read.csv("C:/Users/Zander Kent/Documents/Data Cleaning/sample dataset.csv", header = T, na.strings=c("", " ","NA"))
aaa <- data.frame(aa)

abc <- as.data.frame(apply(aaa, 2, function(x) gsub(" @ ", "at", x)))
write.csv(abc, file="C:/Users/Zander Kent/Documents/Data Cleaning/clean_2.csv")

链接到 google.drive 示例数据中的数据

我尝试了其中一个答案,它在一个非常小的数据集 10x10 上工作,但是当我在整个数据集上尝试它时,它没有做任何事情。 所有的特殊字符都还在那里。 代码运行时没有错误消息,没有任何问题。

缺乏可重现的例子......

让我们用不需要的符号创建一个向量:

a <- data.frame(x = c("1", "a", "3@"), y = c("5@", "2", "b"))

现在我们可以使用gsub

as.data.frame(apply(a, 2, function(x) gsub("@", "at", x)))

并获得:

##    x   y
## 1   1 5at
## 2   a   2
## 3 3at   b

####### 编辑 #####

如果要将“-”替换为“dash”,那么qdap包中有一个不错的功能。 让我们用两个坏人重新创建向量:

a <- data.frame(x = c("1-", "a", "3@"), y = c("5@", "2", "b-"))

然后我们这样做:

require(qdap)
as.data.frame(apply(a, 2, function(x) multigsub(c("@", "-"), 
                                                c("at", "dash"), 
                                                x))

####### 编辑 2 #######

这有效,而且相当大:

x <- sample(LETTERS, 1e6, TRUE)
y <- sample(c("", "", "", "@", "-"), 1e6, TRUE)
a <- data.frame(x, y)
b <- apply(a, 1, function(x) paste(x, collapse = ""))

df <- as.data.frame(matrix(b, ncol=50))
df[1:4, 1:10]
  V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1  T V-  H  L  T K@  M T@ M-   I
2  G  W F@ K@ W@ T@  R X-  G  G-
3  R E@  V O@  R  D  L  L C-   B
4  T G@  J  U  X H@  Q  Q  T  Z@

df2 <- apply(df, 2, function(x) multigsub(c("@", "-"), c("at", "dash"), x))

grep("-", df2)
integer(0)

grep("@", df2)
integer(0)

df2[1:4, 1:10]
     V1  V2      V3    V4    V5    V6    V7  V8      V9      V10    
[1,] "T" "Vdash" "H"   "L"   "T"   "Kat" "M" "Tat"   "Mdash" "I"    
[2,] "G" "W"     "Fat" "Kat" "Wat" "Tat" "R" "Xdash" "G"     "Gdash"
[3,] "R" "Eat"   "V"   "Oat" "R"   "D"   "L" "L"     "Cdash" "B"    
[4,] "T" "Gat"   "J"   "U"   "X"   "Hat" "Q" "Q"     "T"     "Zat" 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM