Вы можете использовать stringr
для извлечения «n =», за которым следует хотя бы одна цифра.Предполагается, что по обе стороны от знака равенства не будет пробелов или одного пробела:
library(stringr)
str_extract_all(x, "n\\s?\\=\\s?\\d+")
[[1]]
[1] "n = 40" "n = 40"
РЕДАКТИРОВАТЬ: Следующее должно работать внутри mutate
с вашим другим условием.Я переключился с stringr
на stringi
, чтобы получить NA
для строки без совпадений.Кроме того, вы могли бы использовать paste
вместо stri_flatten
, но я бы придерживался stri_flatten
, поскольку он сохраняет NA
в качестве пропущенного значения, а не символ "NA"
, как paste
.
sapply(stri_extract_all(x, regex = "n\\s?\\=\\s?\\d+"), stri_flatten, collapse = ", ")
Для регулярных выражений я начал с этого шпаргалки для R (и до сих пор ссылаюсь на него).Вышеупомянутое регулярное выражение работает так:
n
- буква n
\\s?
- не более 1 (?
) пробела (\\s
) (вы можете предпочесть MrFlick'sиспользование *
над ?
- ваш звонок)
\\=
- знак равенства
\\s?
- не более 1 (?
) пробела (\\s
)
\\d+
- одна или несколько (+
) цифр (\\d
)
Данные :
x = c("OBJECTIVES:
In diabetic polyneuropathy (DPN) patients, the effect of folic acid and homocysteine has been related to components of nerve conduction velocity (NCV). The objective of this study was to determine the effect of folic acid supplementation on NCV in DPN patients.
METHODS:
Patients were randomized to receive either 1 mg of folic acid (n = 40) or placebo (n = 40) for 16 weeks. Blood samples were collected to assess serum folic acid and homocysteine concentrations, and NCV was performed for assessment of diabetic neuropathy.
RESULTS:
At 16 weeks, in the supplemented group, serum levels of folic acid (p < 0.001) increased, homocysteine concentrations decreased (p < 0.001), with no change in serum vitamin B12 levels. There was a significant increase in sensory sural amplitude (p < 0.001), and components of motor nerves, including amplitude (p = 0.001) and velocity (p < 0.001), but decreased onset latency of peroneal (p = 0.019) and tibial (p = 0.011) motor nerves.
CONCLUSION:
Our data suggest that supplementation with 1 mg of folic acid for 16 weeks may be useful for enhancing NCV in DPN patients.", "no numbers here", "n = 100")