要从 R 数据框中的字符串中提取数字,我们可以按照以下步骤操作 -
首先,创建一个数据框。
然后,使用 gsub 函数从字符串中提取数字。
让我们创建一个数据框,如下所示 -
x<- sample(c("grp12","grp01","grp05","grp03","grp04","grp09","grp10","grp11","grp02","grp06","grp07","grp08"),25,replace=TRUE) df<-data.frame(x) df输出结果
执行时,上述脚本生成以下内容output(this output will vary on your system due to randomization)-
x 1 grp01 2 grp04 3 grp08 4 grp01 5 grp12 6 grp08 7 grp08 8 grp09 9 grp02 10 grp12 11 grp05 12 grp10 13 grp04 14 grp06 15 grp03 16 grp08 17 grp06 18 grp05 19 grp10 20 grp10 21 grp06 22 grp04 23 grp04 24 grp06 25 grp06
从字符串中提取数字
使用 gsub 函数从数据框 df 中的字符串列 x 中提取数字 -
x<- sample(c("grp12","grp01","grp05","grp03","grp04","grp09","grp10","grp11","grp02","grp06","grp07","grp08"),25,replace=TRUE) df<-data.frame(x) df$Group<-gsub("[^0-9]","",df$x) df输出结果
x Group 1 grp01 01 2 grp04 04 3 grp08 08 4 grp01 01 5 grp12 12 6 grp08 08 7 grp08 08 8 grp09 09 9 grp02 02 10 grp12 12 11 grp05 05 12 grp10 10 13 grp04 04 14 grp06 06 15 grp03 03 16 grp08 08 17 grp06 06 18 grp05 05 19 grp10 10 20 grp10 10 21 grp06 06 22 grp04 04 23 grp04 04 24 grp06 06 25 grp06 06