Reformatting data with a pattern
문제
I have a large dataset with mix of number and alphabets. Just an small example:
sex <- c("M", "F", "F", "M", "M")
ind <- c("I1", "I2", "I3", "I4", "C")
M1 <- c("ab", "bb", "ac", "ad", "dd")
M2 <- c(12, 22, 23, 24, 25)
M3 <- c("AT", "AG", "AC", "GG", "TC")
M4 <- c(22, 23, 24, 14, 24)
mydf <- data.frame(sex, ind, M1, M2, M3, M4)
mydf
sex ind M1 M2 M3 M4
1 M I1 ab 12 AT 22
2 F I2 bb 22 AG 23
3 F I3 ac 23 AC 24
4 M I4 ad 24 GG 14
5 M C dd 25 TC 24
I want to introduce a "/" marks between two characters in columns M1......Mn (end of the file) so that the resulting data frame look like:
sex ind M1 M2 M3 M4
1 M I1 a/b 1/2 A/T 2/2
2 F I2 b/b 2/2 A/G 2/3
3 F I3 a/c 2/3 A/C 2/4
4 M I4 a/d 2/4 G/G 1/4
5 M C d/d 2/5 T/C 2/4
Sorry I was clueless how to proceed ...your help appreciated ...
해결책
One liner:
> data.frame(lapply(mydf, function(x) sub("(.)(.)", "\\1/\\2", x)))
sex ind M1 M2 M3 M4
1 M I/1 a/b 1/2 A/T 2/2
2 F I/2 b/b 2/2 A/G 2/3
3 F I/3 a/c 2/3 A/C 2/4
4 M I/4 a/d 2/4 G/G 1/4
5 M C d/d 2/5 T/C 2/4
다른 팁
All of the cryptic power of R gives you this:
splitInsert
splits a column at each letter usingstrsplit
and recombines it withpaste
. This is wrapped insapply
to vectorise the function.- I then use
lapply
to applysplitInsert
over columns 3:6 of your data.frame, anddata.frame
to combine it with the two columns that you don't want modified. - Note that
splitInsert
is fully general - it will work for text strings of any length, and you can use any new character of choice to recombine the split elements.
The code:
splitInsert <- function(x, split="", new="/"){
sapply(x, function(y)
paste(
strsplit(as.character(y), split=split)[[1]],
collapse=new)
)
}
data.frame(mydf[, 1:2], lapply(mydf[, 3:ncol(mydf)], splitInsert))
The results:
sex ind M1 M2 M3 M4
1 M I1 a/b 1/2 A/T 2/2
2 F I2 b/b 2/2 A/G 2/3
3 F I3 a/c 2/3 A/C 2/4
4 M I4 a/d 2/4 G/G 1/4
5 M C d/d 2/5 T/C 2/4
This seems to work.
m1 <- substr(mydf$M1, start=1, stop=1)
m2 <- substr(mydf$M1, start=2, stop=2)
paste(m1, m2, sep="/")
Output
[1] "a/b" "b/b" "a/c" "a/d" "d/d"
제휴하지 않습니다 StackOverflow