(对不起,如果我使用了错误的术语和格式,这是我的第一篇文章)
我正在尝试从dataframe中提取字符串的一个特定部分。这就是整个细胞的样子:
{温度:6.689724,地理位置(经度):-159.0224,收集日期:2011-10-05/2011-10-06,环境(生物群落):海洋生物群落(ENVO:00000447),环境(特征):中胚轴带(ENVO:00000213),环境(物质):颗粒物质,包括浮游生物(ENVO:xxxxxxxx),环境包装:水,样品采集装置或方法:带CTD (sbe9C)和10 Niskin瓶的玫瑰花取样器,盐度:34.000507,地理位置(纬度):31.528,仪器模型:Illumina Analyzer IIx}
我想要提取粗体部分,并删除之前和之后的一切。我想对列中的每个单元重复这样的操作,我最初的计划是在前面使用str_extract()并删除字符串,并包括"water“,然后再次使用str_extract在”盐度“之后删除字符串。下面是我的尝试,输出结果是,Column1下的所有内容都被删除并替换为NA。
df$Column1 <- str_extract(df$Column1, "(?<=water, )(\\w+)")
事先谢谢你,再次为你的格式感到抱歉.
发布于 2022-06-23 13:10:54
下面是一个基本的R方法,它在逗号处拆分字符串,然后在生成的向量中选择以“示例收集设备”开头的元素。假设x
是该列中的单个字符串。
grep("^sample collection device", unlist(strsplit(x, ",")), value = TRUE, perl = TRUE)
[1] "sample collection device or method:ROSETTE sampler with CTD (sbe9C) and 10 Niskin bottles"
发布于 2022-06-23 13:17:25
如果数据具有相同的长度,并且所需的字符串位于每一行列的相同位置:
library(stringr)
stringyouwant <- str_sub(df$column, startingpositionofstringyouwant, endingpositionofstringyouwant)
发布于 2022-06-23 13:28:25
我将使用datatable来完成它,这样您就可以轻松地处理所有行。
library(data.table)
string<- "{temperature:6.689724,geographic location (longitude):-159.0224,collection date:2011-10-05/2011-10-06,environment (biome):marine biome (ENVO:00000447),environment (feature):mesopelagic zone (ENVO:00000213),environment (material):particulate matter, including plankton (ENVO:xxxxxxxx),environmental package:water,sample collection device or method:ROSETTE sampler with CTD (sbe9C) and 10 Niskin bottles,salinity:34.000507,geographic location (latitude):31.528,instrument model:Illumina Genome Analyzer IIx}}"
dat<- data.frame(String=rbind(string,string))
dat$Substring<- unlist(lapply(dat$String, function(x) data.table::transpose(strsplit(x,','))[9] ))
https://stackoverflow.com/questions/72730613
复制相似问题