向数据框中的数字列添加字符 [英] Add characters to a numeric column in dataframe

查看:105
本文介绍了向数据框中的数字列添加字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数据框:

I have a dataframe like this:

  V1      V2      V3 
1  1 3423086 3423685 
2  1 3467184 3467723 
3  1 4115236 4115672 
4  1 5202437 5203057 
5  2 7132558 7133089 
6  2 7448688 7449283 

我想更改V1列并在数字前添加chr。就像这样:

I want to change the V1 column and add chr before the number. Just like this:

  V1      V2      V3 
1  chr1 3423086 3423685 
2  chr1 3467184 3467723 
3  chr1 4115236 4115672 
4  chr1 5202437 5203057 
5  chr2 7132558 7133089 
6  chr2 7448688 7449283 

在R中有办法吗?

推荐答案

正则表达式模式 ^(在任何字符类括号之外)表示紧接在字符类项目(在其他计算机语言中也称为字符串)。这只是将向量中每个字符元素的开头替换为 chr的词干。

The regex pattern "^" (outside any character-class brackets) represents the point just before the first character of a "character"-class item (aka "string" in other computer languages). This just replaces the beginning of each "character" element in vector with a stem of "chr". It implicitly coerces a "numeric" input value to "character" so alters the mode of the result.

> dat$V1 <- sub("^", "chr", dat$V1 )
> dat
    V1      V2      V3
1 chr1 3423086 3423685
2 chr1 3467184 3467723
3 chr1 4115236 4115672
4 chr1 5202437 5203057
5 chr2 7132558 7133089
6 chr2 7448688 7449283

当然可以使用粘贴( chr,dat $ V1,sep =),但我认为正则表达式解决方案可能更整洁。

Could, of course, have used paste("chr", dat$V1, sep=""), but I thought a regex solution might be neater.

这篇关于向数据框中的数字列添加字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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