admin管理员组文章数量:1318579
I am trying to flip my data each time we see a -
, this is probably best explained in an example;
myDat
"11-11 10-30" "1-1 30-29" "9-8" "1-1 1-1 1-3" "0-1 7-12" "5-8 20-45"
When I flip this on -
I am trying to get;
myDat
"11-11 30-10" "1-1 29-30" "8-9" "1-1 1-1 3-1" "1-0 12-7" "8-5 45-20"
My initial thought was to do this using a gsub or sub and just flip the number each time we see a -
but this was tricky as I have differing lengths, maybe a better was to do it is using strsplit(), splitting on the -
and pasting back together, although I'm not too familiar with that function.
I am trying to flip my data each time we see a -
, this is probably best explained in an example;
myDat
"11-11 10-30" "1-1 30-29" "9-8" "1-1 1-1 1-3" "0-1 7-12" "5-8 20-45"
When I flip this on -
I am trying to get;
myDat
"11-11 30-10" "1-1 29-30" "8-9" "1-1 1-1 3-1" "1-0 12-7" "8-5 45-20"
My initial thought was to do this using a gsub or sub and just flip the number each time we see a -
but this was tricky as I have differing lengths, maybe a better was to do it is using strsplit(), splitting on the -
and pasting back together, although I'm not too familiar with that function.
1 Answer
Reset to default 6You can try gsub
like below
> gsub("(\\d+)-(\\d+)", "\\2-\\1", myDat)
[1] "11-11 30-10" "1-1 29-30" "8-9" "1-1 1-1 3-1" "1-0 12-7"
[6] "8-5 45-20"
If you are interested in the strsplit
-based solution, probably you can take a look at this (although it is much less simple or efficient than gsub
)
sapply(
strsplit(myDat, " "),
\(s) {
paste0(sapply(
strsplit(s, "-"),
\(x) {
paste0(rev(x), collapse = "-")
}
), collapse = " ")
}
)
and it also gives the same output as desired
[1] "11-11 30-10" "1-1 29-30" "8-9" "1-1 1-1 3-1" "1-0 12-7"
[6] "8-5 45-20"
本文标签: rFlip parts of my data which differs in lengthStack Overflow
版权声明:本文标题:r - Flip parts of my data which differs in length - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742046810a2417834.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论