将字符串切成固定宽度字符元素的向量 [英] Chopping a string into a vector of fixed width character elements

查看:11
本文介绍了将字符串切成固定宽度字符元素的向量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含文本字符串的对象:

I have an object containing a text string:

x <- "xxyyxyxy"

我想把它分成一个向量,每个元素包含两个字母:

and I want to split that into a vector with each element containing two letters:

[1] "xx" "yy" "xy" "xy"

似乎 strsplit 应该是我的票,但由于我没有正则表达式 foo,我无法弄清楚如何让这个函数按照我想要的方式将字符串切成块它.我该怎么做?

It seems like the strsplit should be my ticket, but since I have no regular expression foo, I can't figure out how to make this function chop the string up into chunks the way I want it. How should I do this?

推荐答案

使用 substring 是最好的方法:

Using substring is the best approach:

substring(x, seq(1, nchar(x), 2), seq(2, nchar(x), 2))

但这里有一个 plyr 的解决方案:

But here's a solution with plyr:

library("plyr")
laply(seq(1, nchar(x), 2), function(i) substr(x, i, i+1))

这篇关于将字符串切成固定宽度字符元素的向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆