替换数据框中所有出现的字符串 [英] Replace all occurrences of a string in a data frame

查看:205
本文介绍了替换数据框中所有出现的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个没有检测到的数据帧,它们用'<'编码。有时在'<'之后有一个空格,有时候不是例子。 '< 2'或'< 2'。我想删除空间的每一次发生。

I'm working on a data frame that has non-detects which are coded with '<'. Sometimes there is a space after the '<' and sometimes not e.g. '<2' or '< 2'. I'd like to remove every occurrence of the space.

示例:

data <- data.frame(name = rep(letters[1:3], each = 3), var1 = rep('< 2', 9), var2 = rep('<3', 9))

  name var1 var2 
1    a  < 2   <3
2    b  < 2   <3
3    c  < 2   <3

这是我必须到的地方:

我可以提取所有的值并使新的字符串,但是我不能将它们放回数据框。

I can extract all the values and make the new strings but I can't put them back in the data frame.

index <- str_detect(unlist(data), '<')
index <- matrix(index, nrow = 3)

data[index] 
#[1] "< 2" "< 2" "< 2" "<3"  "<3"  "<3" 

replacements <- str_replace_all(data[index], "<[ ]+","<") 
replacements
#[1] "<2" "<2" "<2" "<3" "<3" "<3"

data[index] <- replacements

#Error in `[<-.data.frame`(`*tmp*`, index, value = c("<2", "<2", "<2",  : 
#  unsupported matrix index in replacement


推荐答案

如果您只是寻求替换所有出现的<(带空格)与<(无空格),则可以执行 lapply ta框架,一个 gsub 替换:

If you are only looking to replace all occurrences of "< " (with space) with "<" (no space), then you can do an lapply over the data frame, with a gsub for replacement:

> data <- lapply(data, function(x) {
+                  gsub("< ", "<", x)
+              })
> data
  name var1 var2
1    a   <2   <3
2    a   <2   <3
3    a   <2   <3
4    b   <2   <3
5    b   <2   <3
6    b   <2   <3
7    c   <2   <3
8    c   <2   <3
9    c   <2   <3

这篇关于替换数据框中所有出现的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆