在每行中删除一个多余的字符? [英] Deleting an extra character in each row?

查看:70
本文介绍了在每行中删除一个多余的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量,由于某种原因,R在每个变量的开头添加了一个额外的 X。

I have a variable, and for some reason R has added an extra "X" in the beginning of each. Is this a common occurrence that I could have avoided?

无论如何,下面是我的数据(当前变量存储在列表中):

Anyhow, below is my data (currently the variable is stored in a list):

X1
X5
X33
X37
...

> str(rc1_output)
 chr [1:63, 1:3] "X1" "X5" "X33" "X37" "X52" "X645" "X646" ...
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:63] "X1" "X5" "X33" "X37" ...
  ..$ : chr [1:3] "" "Entropy" "Subseq."

> dput(head(rc1_output))
structure(c("X1", "X5", "X33", "X37", "X52", "X645", "0", "0", 
"0", "0", "0", "0", "0.256010845762264", "0.071412419435563", 
"0.071412419435563", "0.071412419435563", "0.071412419435563", 
"0.071412419435563"), .Dim = c(6L, 3L), .Dimnames = list(c("X1", 
"X5", "X33", "X37", "X52", "X645"), c("", "Entropy", "Subseq."
)))

我如何遍历变量的所有行并删除 X

How can I loop through all rows of the variable and remove the X?

推荐答案

尝试 substr gsub

x <- c("X1", "X354", "X234", "X2134")
substr(x, 2, nchar(x))
# [1] "1"    "354"  "234"  "2134"
gsub("^X", "", x)
# [1] "1"    "354"  "234"  "2134"






更新



好像只是第一列(未命名)和行名一样受到影响。适用相同的一般方法:


Update

It looks like just the first column (which is unnamed) and the rownames are affected. The same general approach applies:

> rc1_output[, 1] <- gsub("^X", "", rc1_output[, 1])
> rc1_output
           Entropy Subseq.            
X1   "1"   "0"     "0.256010845762264"
X5   "5"   "0"     "0.071412419435563"
X33  "33"  "0"     "0.071412419435563"
X37  "37"  "0"     "0.071412419435563"
X52  "52"  "0"     "0.071412419435563"
X645 "645" "0"     "0.071412419435563"

如有必要,重复执行 rownames(rc1_output)的过程,例如:

Repeat the process for rownames(rc1_output) if required, like this:

rownames(rc1_output) <- gsub("^X", "", rownames(rc1_output))

但是,我的猜测是,您可以在代码的早期阶段更有效地解决此问题。如果我们首先知道这些数据是如何以这种形式出现的,那将使诊断变得更加容易。

My guess, however, is that you can solve this problem more effectively at an earlier stage in your code somewhere. If we knew how this data came to be in this form in the first place, that would make it much easier to diagnose.

这篇关于在每行中删除一个多余的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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