替换一个字符串并用另一个字符串创建一列

标签 r string dplyr tidyverse stringr

我有一个如下所示的数据框

position=c("24,201", "8,915", "45,877:1","251,603")
evindence=c("RA", "RA","RA","RA")
test = data.frame(evindence,position)
  evindence position
1        RA   24,201
2        RA    8,915
3        RA 45,877:1
4        RA  251,603

我想使用 stringr 或其他 tidyr 应用程序来替换 ","= "."进而 当存在像“:”这样的字符串时创建一个新列。

我希望我的数据集看起来像这样:

  evindence position insertion
1        RA   24201     NA
2        RA    8915     NA
3        RA   45877     1
4        RA  251603     NA

感谢任何帮助或指导

最佳答案

像这样的事情可能会成功:

 # should remove the "," from the position column
test$position = gsub(",", "", position)
# should check if string contains :
test$insertion = grepl(":", test$position, fixed=TRUE)
# should extract anything before ":"
test$position = sapply(strsplit(test$position, "\\:"), "[", 1)

关于替换一个字符串并用另一个字符串创建一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65905117/

相关文章:

r - mutate() 试图在使用美元符号运算符时使用全局变量的值进行提取

r - 添加两个数据框;相同的维度;不同的顺序列

r - x[[jj]] <- v : attempt to select less than one element in integerOneIndex 中的错误

r - 如何为条形图中的特定条形着色(qplot、ggplot2)

java - 在Java中如何按字符分割字符串?

python - 在 Python 2.7.1 中使用 itertools、yield 和 iter() 生成带有滑动窗口的字符串列表?

从 tibble 中删除子字符串行

java - 将 byte[] 转换为带点的数组的正确方法

r - dplyr和tail更改r中group_by中的最后一个值

将多列中的行 id 的值替换为 dplyr case_when