bio*_*ard 4 r quotation-marks removeall dataframe
我有一个如下所示的数据框rep:
> head(rep)
position chrom value label
[1,] "17408" "chr1" "0" "miRNA"
[2,] "17409" "chr1" "0" "miRNA"
[3,] "17410" "chr1" "0" "miRNA"
[4,] "17411" "chr1" "0" "miRNA"
[5,] "17412" "chr1" "0" "miRNA"
[6,] "17413" "chr1" "0" "miRNA"
Run Code Online (Sandbox Code Playgroud)
如何从所有元素中删除引号?
注意:rep$position并且rep$value应该是numerictype,rep$chrom并且rep$label应该是charactertype.
两步:1)去掉引号,2)相应地转换列:
数据
x <- read.table(text='
position chrom value label
"\\"17408\\"" "\\"chr1\\"" "\\"0\\"" "\\"miRNA\\""
"\\"17409\\"" "\\"chr1\\"" "\\"0\\"" "\\"miRNA\\""'
, header=T)
Run Code Online (Sandbox Code Playgroud)
1)摆脱引号
library(stringr)
library(plyr)
del <- colwise(function(x) str_replace_all(x, '\"', ""))
x <- del(x)
Run Code Online (Sandbox Code Playgroud)
2)相应地转换列
num <- colwise(as.numeric)
x[c(1,3)] <- num(x[c(1,3)])
x
position chrom value label
1 17408 chr1 0 miRNA
2 17409 chr1 0 miRNA
Run Code Online (Sandbox Code Playgroud)
如@Roland所示,你有一个matrix,而不是一个data.frame,它们有不同的默认print方法.坚持使用matrix,您可以quote = FALSE明确设置print或使用noquote.
这是一个基本的例子:
## Sample data
x <- matrix(c(17, "chr1", 0, "miRNA", 18, "chr1", 0, "miRNA"), nrow = 2,
byrow = TRUE, dimnames = list(
NULL, c("position", "chrom", "value", "label")))
## Default printing
x
# position chrom value label
# [1,] "17" "chr1" "0" "miRNA"
# [2,] "18" "chr1" "0" "miRNA"
## Two options to make the quotes disappear
print(x, quote = FALSE)
# position chrom value label
# [1,] 17 chr1 0 miRNA
# [2,] 18 chr1 0 miRNA
noquote(x)
# position chrom value label
# [1,] 17 chr1 0 miRNA
# [2,] 18 chr1 0 miRNA
Run Code Online (Sandbox Code Playgroud)
此外,正如您自己想出的那样,将您转换matrix为a data.frame会使引号消失.data.frame如果每列是不同类型的数据(数字,字符,因子等),则A 是更合适的结构来保存数据.但是,将a转换matrix为a data.frame不会自动为您转换列.相反,您可以使用type.convert(在创建data.frame使用read.table和族时也使用):
y <- data.frame(x, stringsAsFactors = FALSE)
str(y)
# 'data.frame': 2 obs. of 4 variables:
# $ position: chr "17" "18"
# $ chrom : chr "chr1" "chr1"
# $ value : chr "0" "0"
# $ label : chr "miRNA" "miRNA"
y[] <- lapply(y, type.convert)
str(y)
# 'data.frame': 2 obs. of 4 variables:
# $ position: int 17 18
# $ chrom : Factor w/ 1 level "chr1": 1 1
# $ value : int 0 0
# $ label : Factor w/ 1 level "miRNA": 1 1
y
# position chrom value label
# 1 17 chr1 0 miRNA
# 2 18 chr1 0 miRNA
Run Code Online (Sandbox Code Playgroud)