字符向量被强制 [英] Character vector is being coerced
问题描述
我正在执行此简单命令,该命令使用字符串"A",并使用空格将其拆分为单词.现在,将此单词向量传递给replace方法,在该方法中,它将看起来像完整数字的所有内容替换为"P12".但是最后的操作使输出变得混乱
I am doing this simple command where it takes a string "A" and splits it into words using space. Now pipe this vector of words to a replace method where it replaces anything that looks like a complete number to "P12". But the output is getting messy by doing the last operation
A <- list(c("a12, 34, 35, 46"),c("ab14, 44, 55, 66"))
B <- stringr::str_split(A, "[[:space:]]") %>% str_replace(pattern = "^[:digit:]{1,}[,]{1}$", replacement = "p12")
输出:
[1] "c(\"a12,\", \"34,\", \"35,\", \"46\")"
已更新:所需的输出应包含两个字符向量,这些向量存储在名为B的列表中:
Updated: desired output should contain two character vectors stored in a list named B:
[1] list(c("a12", "34", "35", "46"), c("ab14", "44", "55", "66"))
已回答了这一部分.谢谢! 还请帮助正则表达式.当我使用下面的命令时,46并没有被替换.我应该如何确保1)文本是一个完整的数字,后跟一个逗号,或者没有逗号被"p12"替换?
This part is answered. Thank you! Also please help with regex. When I use the command below, 46 is not being replaced. How should I ensure if 1) the text is a complete number followed by a comma or no comma gets replaced by "p12"
str_replace(c("a12,", "34,", "35,", "46"), pattern = "^[:digit:]{1,}[,]{1}$", replacement = "p12")
输出:
"a12," "p12" "p12" "46"
所需:
"a12," "p12" "p12" "p12"
任何帮助将不胜感激
推荐答案
str_split
返回字符向量列表.您只想unlist()
.它不直观,但是可以处理字符向量输入(每个元素一个列表).
str_split
returns a list of character vectors. You just want to unlist()
. It's not intuitive, but it's so it can handle a character vector input (one list for every element).
关于正则表达式,最后一个数字没有逗号.尝试让它与0或1个逗号匹配:
Regarding the regex, there isn't a comma on the final number. Try allowing it to match with 0 or 1 commas:
library(dplyr)
library(stringr)
A <- "a12, 34, 35, 46"
str_split(A, "[[:space:]]") %>%
unlist() %>%
str_replace(pattern = "^[:digit:]{1,}[,]{0,1}$", replacement = "p12")
输出:
#[1] "a12," "p12" "p12" "p12"
这篇关于字符向量被强制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!