提取字符串中的前 2 个字符 [英] Extract the first 2 Characters in a string

查看:149
本文介绍了提取字符串中的前 2 个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要提取字符串中的前 2 个字符,以便稍后创建 bin 图分布.向量:

I need to extract the 1st 2 characters in a string to later create bin plot distribution. vector:

x <- c("75 to 79", "80 to 84", "85 to 89") 

我已经走到这一步了:

substrRight <- function(x, n){
  substr(x, nchar(x)-n, nchar(x))
}

调用函数

substrRight(x, 1)

回复

[1] "79" "84" "89"

需要打印最后 2 个字符而不是第一个.

Need to prints the last 2 characters not the first.

[1] "75" "80" "85"

推荐答案

你可以直接使用 substr 函数来取每个字符串的前两个字符:

You can just use the substr function directly to take the first two characters of each string:

x <- c("75 to 79", "80 to 84", "85 to 89")
substr(x, start = 1, stop = 2)
# [1] "75" "80" "85"

您还可以编写一个简单的函数来执行反向"子字符串,假设索引从字符串末尾开始,则给出 'start' 和 'stop' 值:

You could also write a simple function to do a "reverse" substring, giving the 'start' and 'stop' values assuming the index begins at the end of the string:

revSubstr <- function(x, start, stop) {
  x <- strsplit(x, "")
  sapply(x, 
         function(x) paste(rev(rev(x)[start:stop]), collapse = ""), 
         USE.NAMES = FALSE)
}
revSubstr(x, start = 1, stop = 2)
# [1] "79" "84" "89" 

这篇关于提取字符串中的前 2 个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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