Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 使用gsub提取文本_R_Text - Fatal编程技术网

R 使用gsub提取文本

R 使用gsub提取文本,r,text,R,Text,我正在建立一个自动数据分析程序,在该程序的最后,我想自动提取已分析文件的名称。我有一个数据框,其中一列包含名称,样式如下: 基线/细胞线2\uKB\u 1813\u B\u基线 剂量0001/细胞线3KB1720\u 1\u 0001 剂量0010/细胞线1KB1810 mat\u0010 我只想在单独的一列中提取粗体字:“KB_1813_B”、“KB1720_1”和“KB1810 mat” 我将gsub与以下命令一起使用: df$column.with.names <- gsub("

我正在建立一个自动数据分析程序,在该程序的最后,我想自动提取已分析文件的名称。我有一个数据框,其中一列包含名称,样式如下:

  • 基线/细胞线2\uKB\u 1813\u B\u基线
  • 剂量0001/细胞线3KB1720\u 1\u 0001
  • 剂量0010/细胞线1KB1810 mat\u0010
我只想在单独的一列中提取粗体字:“KB_1813_B”、“KB1720_1”和“KB1810 mat”

我将gsub与以下命令一起使用:

df$column.with.names <- gsub(".*KB|_.*", "KB", df$column.with.new.names)

df$column.with.names我们可以使用
stru extract

library(stringr)
str_extract(df$column.with.new.names, "KB_*\\d+[_ ]*[^_]*")
#[1] "KB_1813_B"  "KB1720_1"   "KB1810 mat"

或者,相同的模式可以通过
sub

sub(".*(KB_*\\d+[_ ]*[^_]*).*", "\\1", df$column.with.new.names)
#[1] "KB_1813_B"  "KB1720_1"   "KB1810 mat"
数据
df我们可以使用
stru-extract

library(stringr)
str_extract(df$column.with.new.names, "KB_*\\d+[_ ]*[^_]*")
#[1] "KB_1813_B"  "KB1720_1"   "KB1810 mat"

或者,相同的模式可以通过
sub

sub(".*(KB_*\\d+[_ ]*[^_]*).*", "\\1", df$column.with.new.names)
#[1] "KB_1813_B"  "KB1720_1"   "KB1810 mat"
数据
df方法是使用正则表达式组:

x <- c("Baseline/Cell_Line_2_KB_1813_B_Baseline",
"Dose 0001/Cell_Line_3_KB1720_1_0001",
"Dose 0010/Cell_Line_1_KB1810 mat_0010")

gsub("^.+Cell_Line_._(.+)_.+$", "\\1", x)
[1] "KB_1813_B"  "KB1720_1"   "KB1810 mat"

x方法是使用正则表达式组:

x <- c("Baseline/Cell_Line_2_KB_1813_B_Baseline",
"Dose 0001/Cell_Line_3_KB1720_1_0001",
"Dose 0010/Cell_Line_1_KB1810 mat_0010")

gsub("^.+Cell_Line_._(.+)_.+$", "\\1", x)
[1] "KB_1813_B"  "KB1720_1"   "KB1810 mat"

x您好,谢谢您的回复。有了这段代码,我可以解决95%的问题,但没有提取出两种类型的名称。两个示例:KB1820_基线,我只想提取其中的KB1820_和KB1890_0002,我只想提取其中的KB1890_Hi,谢谢您的回复。有了这段代码,我可以解决95%的问题,但没有提取出两种类型的名称。两个示例:KB1820_基线,我只想提取其中的KB1820_和KB1890_0002,我只想提取其中的KB1890_