【问题标题】:Replace the string value with value in the find list in R将字符串值替换为 R 中查找列表中的值
【发布时间】:2017-03-09 00:36:29
【问题描述】:

我有一个数据集,其中包含类似

的列
   string<-c('lib1_Rstudio_case1','lib2_Rstudio_case1and2','lib5_python_notthe correct_language','lib3_Jupyter_really_good','lib1_spyder_nice','lib1_R_the_core')
   replacement<-c('Rstudio','Jupyter','spyder','R')

我想替换与替换值匹配的字符串值 id。我现在正在使用以下代码

gsub(paste(replacement, collapse = "|"), replacement = replacement, x = string)

这是我用来查找案例的另一段代码

string[grepl(paste(replacement, collapse='|'), string, ignore.case=TRUE)]

我想更新我找到的那些 我希望输出像

Rstudio,Rstudio,'',Jupyter,spyder,R

我不想通过硬编码来做到这一点。我想编写一个可扩展的代码。

非常感谢任何帮助

提前致谢

【问题讨论】:

  • 试试ifelse((x &lt;- sub('.*_', '', string)) %in% replacement, x, '')
  • 这个代码对我来说但是我不能替换任何东西 grep(paste(replacement, collapse='|'), string, ignore.case=TRUE)]
  • 对不起。我会尝试编辑问题

标签: r replace gsub qdap


【解决方案1】:

使用gsub函数隔离id,然后通过is.na函数找到与replacement长度不匹配的id。然后将识别的id替换为空字符''

编辑:由于您更改了问题中的字符串数据,因此我修改了gsub 函数。 gsub 函数中使用的模式将在 lib 文本之后找到数值并省略字符串元素的其余部分。

replacement<-c('Rstudio','Jupyter','spyder','R')

string<-c('lib1_Rstudio','lib2_Rstudio','lib5_python','lib3_Jupyter','lib1_spyder','lib1_R')
index <- is.na( replacement[ as.integer( gsub( "lib([[:digit:]])*[[:alnum:]_\ ]*", "\\1", string)) ] )
a1 <- sapply( strsplit(string, "_"), function( x ) x[2] )
a1[ index ] <- ''
a1
# [1] "Rstudio" "Rstudio" ""        "Jupyter" "spyder"  "R"    

string <- c('lib1_Rstudio_case1','lib2_Rstudio_case1and2','lib5_python_notthe correct_language','lib3_Jupyter_really_good','lib1_spyder_nice','lib1_R_the_core')
index <- is.na( replacement[ as.integer( gsub( "lib([[:digit:]])*[[:alnum:]_\ ]*", "\\1", string)) ] )
a1 <- sapply( strsplit(string, "_"), function( x ) x[2] )
a1[ index ] <- ''
a1
# [1] "Rstudio" "Rstudio" ""        "Jupyter" "spyder"  "R"

【讨论】:

  • 我更改了字符串的等级,如string&lt;-c('lib1_Rstudio','lib2_python','lib5_Rstudio','lib3_Jupyter','lib1_spyder','lib1_R'),返回错误结果"Rstudio" "python" "" "Jupyter" "spyder" "R" 。你能告诉我为什么错了吗?
  • id 5 大于replacement 的长度,这就是第三个元素lib5_Rstudio 变成'' 空字符的原因
  • replacement的长度是4,因为这个字符向量中有4个元素-replacement
  • 感谢您的解释。
  • 感谢您的解释
【解决方案2】:

这是我使用的另一个简单代码。那不需要正则表达式功能。感谢您的帮助

string<-c('lib1_Rstudio_case1','lib2_Rstudio_case1and2','lib5_python_notthe correct_language','lib3_Jupyter_really_good','lib1_spyder_nice','lib1_R_the_core')
replacement<-c('R','Jupyter','spyder','Rstudio')
replaced=string
replaced=''


for (i in 1:length(replacement))
{
  replaced[which(grepl(replacement[i],string))]=replacement[i]
}
replaced[is.na(replaced)]=''

【讨论】:

    猜你喜欢
    • 2011-03-09
    • 2016-01-20
    • 1970-01-01
    • 1970-01-01
    • 2020-01-03
    • 2015-06-27
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多