Извлечение текста из абзаца между двумя символами в R - PullRequest
1 голос
/ 01 июля 2019

У меня есть абзац текста, и я хотел бы извлечь из него каждый размер выборки. Обычно я могу заставить Regex работать, но я не могу.

Вот пример:

x = "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."

Я хотел бы извлечь два размера выборки. В этом случае n = 40 и n = 40.

Я пытался

gsub('.*[n=]|).*','',x)

Я вернусь ts.

Ответы [ 4 ]

2 голосов
/ 01 июля 2019

Вот один из способов извлечь эти значения

regmatches(x, gregexpr('n\\s*=\\s*\\d+',x))

здесь мы ищем n = (с возможными пробелами вокруг знака равенства) и затем извлекаем их с помощью regmatches.

1 голос
/ 01 июля 2019

Уродливое решение без регулярных выражений может быть:

#first "n = "
substr(strsplit(x, "n = ",fixed=T)[[1]][2],1,2)
#second "n = "
substr(strsplit(x, "n = ",fixed=T)[[1]][3],1,2)
0 голосов
/ 01 июля 2019

Способ получить число в скобках выглядит следующим образом:

library(stringr)

lapply(str_split(x,pattern="\\("),function(x) gsub('(.*)\\).*','\\1',x))
[[1]]
 [1] "OBJECTIVES:\n\nIn diabetic polyneuropathy "
 [2] "DPN"                                       
 [3] "NCV"                                       
 [4] "n = 40"                                    
 [5] "n = 40"                                    
 [6] "p < 0.001"                                 
 [7] "p < 0.001"                                 
 [8] "p < 0.001"                                 
 [9] "p = 0.001"                                 
[10] "p < 0.001"                                 
[11] "p = 0.019"                                 
[12] "p = 0.011"    

Вы разбиваете текст, используя \ (в качестве шаблона), и применяете gsub в каждом его фрагменте. После этого вы можете использовать grep, чтобы определить, какие элементы начинаются с "n =", чтобы получить тот, который вам нужен.

Надеюсь, это поможет

0 голосов
/ 01 июля 2019

Вы можете использовать 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")
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...