在第一个和最后一个逗号上拆分字符串 [英] split strings on first and last commas
问题描述
我想在第一个和最后一个逗号上拆分字符串.每个字符串至少有两个逗号.下面是一个示例数据集和所需的结果.
I would like to split strings on the first and last comma. Each string has at least two commas. Below is an example data set and the desired result.
这里有一个类似的问题询问如何在第一个逗号上拆分:在第一个逗号上拆分在字符串中
A similar question here asked how to split on the first comma: Split on first comma in string
这里我问了如何在前两个冒号上拆分字符串:首先拆分字符串两个冒号
Here I asked how to split strings on the first two colons: Split string on first two colons
感谢您的任何建议.我更喜欢基本 R 中的解决方案.抱歉,如果这是重复的.
Thank you for any suggestions. I prefer a solution in base R. Sorry if this is a duplicate.
my.data <- read.table(text='
my.string some.data
123,34,56,78,90 10
87,65,43,21 20
a4,b6,c8888 30
11,bbbb,ccccc 40
uu,vv,ww,xx 50
j,k,l,m,n,o,p 60', header = TRUE, stringsAsFactors=FALSE)
desired.result <- read.table(text='
my.string1 my.string2 my.string3 some.data
123 34,56,78 90 10
87 65,43 21 20
a4 b6 c8888 30
11 bbbb ccccc 40
uu vv,ww xx 50
j k,l,m,n,o p 60', header = TRUE, stringsAsFactors=FALSE)
推荐答案
这里有一个比较简单的方法.在第一行中,我们使用 sub
用分号替换第一个和最后一个逗号,产生 s
.然后我们使用 sep=";"
读取 s
,最后 cbind
将 my.data
的其余部分读取到它:
Here is a relatively simple approach. In the first line we use sub
to replace the first and last commas with semicolons producing s
. Then we read s
using sep=";"
and finally cbind
the rest of my.data
to it:
s <- sub(",(.*),", ";\\1;", my.data[[1]])
DF <- read.table(text=s, sep =";", col.names=paste0("mystring",1:3), as.is=TRUE)
cbind(DF, my.data[-1])
给予:
mystring1 mystring2 mystring3 some.data
1 123 34,56,78 90 10
2 87 65,43 21 20
3 a4 b6 c8888 30
4 11 bbbb ccccc 40
5 uu vv,ww xx 50
6 j k,l,m,n,o p 60
这篇关于在第一个和最后一个逗号上拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!