我有两个向量:
presidents = c("Bill Clinton", "George Bush", "Ronald Reagan", "Jimmy Carter", "Gerald Ford")
vice.presidents = vice.presidents = c("Al Gore", "Dan Quayle", "George Bush","Walter Mondale", "Nelson Rockefeller")
我正在尝试使用substr()
形式的"Clinton+Quayle", "Bush+..."
获得结果,其中只有姓氏,并且随机选择的总统与随机选择的副总裁配对。
答案 0 :(得分:2)
请尝试以下操作。
set.seed(1843)
p <- sapply(strsplit(presidents, " "), '[', 2)
vp <- sapply(strsplit(vice.presidents, " "), '[', 2)
n <- 5
paste(sample(p, n, TRUE), sample(vp, n, TRUE))
首先,用空格分割名称,只保留第二部分,即姓氏 然后,从结果向量中随机抽样并将它们粘贴在一起。
答案 1 :(得分:0)
stringr
包的解决方案
presidents = c("Bill Clinton", "George Bush", "Ronald Reagan", "Jimmy Carter", "Gerald Ford")
vice.presidents = c("Al Gore", "Dan Quayle", "George Bush","Walter Mondale", "Nelson Rockefeller")
library(stringr)
str_c(sample(str_extract(presidents, pattern = "\\b[[:alpha:]]*\\b$")),
sample(str_extract(vice.presidents, pattern = "\\b[[:alpha:]]*\\b$")),
sep = "+")
#> [1] "Bush+Bush" "Reagan+Mondale" "Ford+Rockefeller"
#> [4] "Carter+Gore" "Clinton+Quayle"
\\b
是字边界的分隔符[[:alpha:]]
是A到z的一个字母*
与前一个字符零或更多时间匹配$
分隔字符链的末尾\\b[:alpha:]\\b$
匹配最后一个单词,这里是姓氏purrr
tidyverse
的功能编程的解决方案
这只是使用管道语法
重写上一个答案library(stringr)
library(purrr)
list(presidents, vice.presidents) %>%
map(sample) %>%
map(str_extract, pattern = "\\b[[:alpha:]]+\\b$") %>%
invoke(str_c, ., sep = "+")
#> [1] "Reagan+Quayle" "Clinton+Bush" "Carter+Mondale"
#> [4] "Ford+Gore" "Bush+Rockefeller"