【发布时间】:2021-05-14 17:56:02
【问题描述】:
我对字符串操作相当陌生,但我遇到了一个关于 R 数据帧中字符串和字符数据的问题。我试图从长字符串中提取数值在模式之后,然后将结果作为新列存储在我的数据框中。我有一个相当大的数据集,我试图找出一些有用的信息,这些信息存储在一个名为“notes”的列中。
例如,我感兴趣的字符串总是遵循这种模式(任务没有什么意义):
df$notes[1] <- "On 5 June, some people walked down the street in this area. [size=around 5]"
df$notes[2] <- "On 6 June, some people rode bikes down the street in this area. [size= nearly 4]"
df$notes[3] <- "On 7 June, some people walked into a grocery store in this area. [size= about 100]"
在某些列中,我们没有得到数值,这是我在得到解决方案后可以处理的问题。这些行遵循与此类似的内容:
df$notes[4] <- "On 10 July, an hundreds of people drank water from this fountain [size=hundreds]"
df$notes[5] <- "on 15 August, an unreported amount of people drove their cars down the street. [size= no report]"
我试图在“size= (some quantifier)”之后提取整个匹配项,并将值存储到我的数据框的附加列中。
最后,我需要在我的数据框中编写一个遍历该列(称为“notes”)的循环,并将值“5、4、100”存储到一个新列中(称为“est_size”)。
理想情况下,我的新专栏将如下所示:
df$est_size[1] <- "around 5"
df$est_size[2] <- "nearly 4"
df$est_size[3] <- "about 100"
df$est_size[4] <- "hundreds"
df$est_size[5] <- "no report"
我尝试过/坚持的代码:
stringr::str_extract(notes[1], \w[size=]\d"
但我得到的只是 "size=" 而不是 after
的值提前感谢您的帮助!
【问题讨论】: