Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

r - Split a column to multiple columns

I have table that the first column is:

chr10:100002872-100002872
chr10:100003981-100003981
chr10:100004774-100004774
chr10:100005285-100005285
chr10:100007123-100007123

I want to convert it to 3 separate columns but I couldn't define ":" and "-" to used strsplit command. What should I do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's one way:

library(data.table)
DF[, paste0("V1.",1:3) ] <- tstrsplit(DF$V1, ":|-")

#                          V1  V1.1      V1.2      V1.3
# 1 chr10:100002872-100002872 chr10 100002872 100002872
# 2 chr10:100003981-100003981 chr10 100003981 100003981
# 3 chr10:100004774-100004774 chr10 100004774 100004774
# 4 chr10:100005285-100005285 chr10 100005285 100005285
# 5 chr10:100007123-100007123 chr10 100007123 100007123

strsplit accepts regular expressions involving the "or" operator, |, as @AnandaMahto said. tstrsplit is just a convenience function added by the data.table package.

If you convert your data.frame to a data.table (which has many advantages and no disadvantages except a slight learning curve), you would do:

setDT(DF)[, paste0("V1.",1:3) := tstrsplit(V1, ":|-")]

#                           V1  V1.1      V1.2      V1.3
# 1: chr10:100002872-100002872 chr10 100002872 100002872
# 2: chr10:100003981-100003981 chr10 100003981 100003981
# 3: chr10:100004774-100004774 chr10 100004774 100004774
# 4: chr10:100005285-100005285 chr10 100005285 100005285
# 5: chr10:100007123-100007123 chr10 100007123 100007123

Alternatives. There are (cumbersome) ways to get the same thing in base R, like

DF[, paste0("V1.",1:3) ] <- do.call(rbind, strsplit(DF$V1, ":|-"))

And @AnandaMahto's package also has a convenience function for this:

library(splitstackshape)
cSplit(DF, "V1", ":|-")
#     V1.1      V1.2      V1.3                      V1_1
# 1: chr10 100002872 100002872 chr10:100002872-100002872
# 2: chr10 100003981 100003981 chr10:100003981-100003981
# 3: chr10 100004774 100004774 chr10:100004774-100004774
# 4: chr10 100005285 100005285 chr10:100005285-100005285
# 5: chr10 100007123 100007123 chr10:100007123-100007123

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...