我想删除多个向量中的所有重复项,不留下任何重复项。例如,对于这些向量:
a <- c("dog", "fish", "cow")
b <- c("dog", "horse", "mouse")
c <- c("cat", "sheep", "mouse")
预期结果是:
a <- c("fish", "cow")
b <- c("horse")
c <- c("cat", "sheep")
有没有办法实现这一点,而无需连接向量并再次拆分它们?
我有一串文本和一系列单词:
String: Auch ein blindes Huhn findet einmal ein Korn.
Words: auch, ein, sehendes
我想检查字符串中包含哪些单词。preg_match_all
为此我使用了:
$pattern = "/\bauch\b|\bein\b|\bsehendes\b/i";
$subject = "Auch ein blindes Huhn findet einmal ein Korn.";
preg_match_all($pattern, $subject, $matches);
print_r($matches);
Array
(
[0] => Array
(
[0] => Auch
[1] => ein
[2] => ein
)
)
这按预期工作,但由于我必须经常编辑模式,并且当单词都被单词边界锚点 ( \b
) 包围时,我发现查找和替换单词会令人困惑,所以我想定义没有单词边界锚点的单词列表,然后在第二步中添加它们。类似于:
$pattern = "auch|ein|sehendes";
$pattern = "/\b" . $pattern . "\b/i";
当然,这并不像预期的那样有效。
我可以用单词填充一个数组并循环遍历它来构建模式,但我想避免循环。有什么想法可以快速完成此操作吗?实际字符串和实际单词数量相当大。
最后我需要匹配的数量,因为它由 返回preg_match_all
。例如,预期输出为“3”。
这是一个类似的问题,用 Javascript 来实现:Apply a word-boundary anchor to all tokens in a single regex
我有一串文本和一个单词向量:
String: "Auch ein blindes Huhn findet einmal ein Korn."
Vector: "auch", "ein"
我想检查向量中每个单词在字符串中的出现频率,并计算频率之和。例如,正确的结果应该是3。
我已经能够检查字符串中出现哪些单词并计算总和:
library(stringr)
deu <- c("\\bauch\\b", "\\bein\\b")
str_detect(tolower("Auch ein blindes Huhn findet einmal ein Korn."), deu)
[1] TRUE TRUE
sum(str_detect(tolower("Auch ein blindes Huhn findet einmal ein Korn."), deu))
[1] 2
不幸的是str_detect
,它不返回出现的次数(1, 2
),而只返回单词是否出现在字符串中(TRUE, TRUE
),所以输出的总和str_detect
不等于单词的数量。
preg_match_all
R 中是否有类似于PHP 的函数?
preg_match_all("/\bauch\b|\bein\b/i", "Auch ein blindes Huhn findet einmal ein Korn.", $matches);
print_r($matches);
Array
(
[0] => Array
(
[0] => Auch
[1] => ein
[2] => ein
)
)
echo preg_match_all("/\bauch\b|\bein\b/i", "Auch ein blindes Huhn findet einmal ein Korn.", $matches);
3
我想避免循环。
我看过很多类似的问题,但它们要么不计算出现次数,要么不使用模式向量进行搜索。我可能忽略了一个回答我的问题的问题,但在你将其标记为重复之前,请确保“重复”实际上问的是完全相同的问题。谢谢。
我有一个数据表,其中有一列包含日期:
> dat
Var1 Var2
<Date> <num>
1: 2023-11-01 18.05
2: 2023-12-01 4.65
3: 2024-01-01 20.34
4: 2024-02-01 21.71
5: 2024-03-01 51.60
6: 2024-04-01 55.54
7: 2024-05-01 50.34
8: 2024-06-01 45.90
9: 2024-07-01 21.26
10: 2024-08-01 19.52
> dput(dat)
structure(list(Var1 = structure(c(19662, 19692, 19723, 19754,
19783, 19814, 19844, 19875, 19905, 19936), class = "Date"), Var2 = c(18.05,
4.65, 20.34, 21.71, 51.6, 55.54, 50.34, 45.9, 21.26, 19.52)), row.names = c(NA,
-10L), class = c("data.table", "data.frame"))
我想要一个包含每年最低日期的行的行号向量,在本例中:
> first.dates
[1] 1 3
我怎样才能找到这些?
在数据框中,当我使用将 NA 替换为 0 时obt[is.na(obt)] <- 0
,列类型从整数变为数字。
str(obt)
...
$ Units: int NA NA 2 1 NA NA NA 1 NA NA ...
obt[is.na(obt)] <- 0
str(obt)
...
$ Units: num 0 0 2 1 0 0 0 1 0 0 ...
我怎样才能避免这种情况?
样本数据:
obt <- structure(list(Date = structure(c(19677, 19678, 19679, 19680,
19681, 19682, 19683, 19684, 19685, 19686), class = "Date"), Title = structure(c(NA,
NA, 3L, 3L, NA, NA, NA, 3L, NA, NA), levels = c("A", "D", "L",
"C"), class = "factor"), Units = c(NA, NA, 2L, 1L, NA, NA, NA,
1L, NA, NA)), row.names = c(NA, 10L), class = "data.frame")