R:如何去除或替换列 R

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

我试过用

df2$y1<-gsub("*","0",as.character(df2$y1)) 

将我的ip数据中的*替换为0,但根本没有用。相反,它为 ip 创建了这个:

[665] "0201080.01010.0107060.0*0"   "0202030.08070.0109070.0*0"  
 [667] "0101040.0202010.0108030.0*0" "0101070.02060.0109080.0*0"  
 [669] "0101090.060.07040.0*0"       "0200020.0200040.04080.0*0"  
 [671] "0103070.0103020.0205000.0*0" "0103070.0103020.0205000.0*0"

请帮忙,谢谢!!!

我想要它看起来像这样:

1.115.193.0 
r gsub
1个回答
0
投票

您必须使用 \ 转义 *,因为它是正则表达式中用于字符串搜索模式的符号(gsub/grepl 中的“pattern”变量等。使用它工作):

第一种情况让我们将 * 替换为您提到的 0,尽管结果看起来不像您预期的那样:

# first we set up the dummy data
v <- "0202030.08070.0109070.0*0"

gsub("\\*","0", v) 
[1] "0202030.08070.0109070.000"

我们可以做的是替换 * 和 0,尽管你最后仍然缺少一个零:

gsub("\\*|0","", v) 
[1] "223.87.197."

所以我们可以使用

ifelse
grepl
像这样工作:

intermed <- gsub("\\*|0","", v) 
# detect if a string ends with a . (has to be escaped and $ stands for end of astring in regex)
# if found string pattern paste 0 to end of intermediate IP
ifelse(grepl(pattern = "\\.$", intermed), paste0(intermed, 0), intermed)
[1] "223.87.197.0"
© www.soinside.com 2019 - 2024. All rights reserved.