从r外的复制列表中提取一些字符串到字符变量中

i5desfxk  于 2023-04-27  发布在  其他
关注(0)|答案(2)|浏览(109)

我正在寻找一种方法来转换特定的话从一个列表以外的R字符串的字符向量。我需要这个,因为我做一些正则表达式的工作,这些话将被用作过滤条件的 Dataframe 。
例如,假设我有一系列未加引号的单词(例如,如果我要在r-studio的源屏幕中输入):

audi
chevrolet
honda
ford

我想把上面的变成:

strings = c("audi","chevrolet","honda","ford")

然后,我可以在下面的过滤器中使用它:

mpg %>% filter(manufacturer %in% strings)

上面的用法只是一个例子。我真的在寻找一种方法,将未引用的文本(已经手动输入到R中或复制粘贴到R中)转换成逗号分隔的字符向量,可以用于各种事情。另外,在R中没有注解的未引用文本是什么?

46scxncf

46scxncf1#

使用 readLines

strings  <- readLines(con = textConnection("audi
chevrolet
honda
ford"))

strings
#[1] "audi"      "chevrolet" "honda"     "ford"

我们也可以使用RStudio Multiple Cursors,并查看相关文章:Fastest way to edit multiple lines of code at the same time

62lalag4

62lalag42#

str_split from stringer也是一个选项。
你可以复制过去你的字符串到一个r字符变量,你可以看到\n换行是你的分割模式

library(stringr)
st="audi
chevrolet
honda
ford"
cat(st)
#> audi
#> chevrolet
#> honda
#> ford
print(st)
#> [1] "audi\nchevrolet\nhonda\nford"
st2=str_split(st,pattern = "\\n")[[1]]
print(st2)
#> [1] "audi"      "chevrolet" "honda"     "ford"

创建于2023-04-19带有reprex v2.0.2

相关问题