如何将字符矩阵转换为数字,将第一列保留为行名:R
How to convert character matrix to numeric, keeping first column as row name: R
下面有这个矩阵,应用循环将行名称更改为数字。
这是矩阵:
treatmenta treatmentb
John Smith NA " 2"
John Doe "16" "11"
Mary Johnson " 3" " 1"
和此代码 as.matrix(apply(y, 2, as.numeric))
结果是这样,但我希望行名是人名
treatmenta treatmentb
[1,] NA 2
[2,] 16 11
[3,] 3 1
转换为 data.table 也不起作用。我该怎么做?
这里是重现数据的代码:
name <- c("John Smith", "John Doe", "Mary Johnson")
treatmenta <- c("NA", "16", "3")
treatmentb <- c("2", "11", "1")
y <- data.frame(name, treatmenta, treatmentb)
rownames(y) <- y[,1]
y[,1] <- NULL
我们可以做到
y <- `dimnames<-`(`dim<-`(as.numeric(y), dim(y)), dimnames(y))
y
# treatmenta treatmentb
#John Smith NA 2
#John Doe 16 11
#Mary Johnson 3 1
或者一个紧凑的选项是
class(y) <- "numeric"
数据
y <- structure(c(NA, "16", " 3", " 2", "11", " 1"), .Dim = c(3L, 2L
), .Dimnames = list(c("John Smith", "John Doe", "Mary Johnson"
), c("treatmenta", "treatmentb")))
您正在从更通用的数据形式(数据帧)转向矩阵(具有暗淡属性的向量)。在此 as.matrix 或任何将数据转换为矩阵的基础方法中,最终将调用 vector(x) 这是通用函数,将所有变量设置为字符,或者将所有内容设置为数字,但名称列设置为 NA(取决于关于你如何称呼 as.matrix)。
话虽如此,如果由于某种原因你仍然必须使用矩阵形式,那么使用它以获得更好的可读性:
treatmenta <- c("1", "16", "3")
treatmentb <- c("2", "11", "1")
y[,1] <- as.matrix(sapply(treatmenta, as.numeric))
y[,2] <- as.matrix(sapply(treatmentb, as.numeric))
#now they are not factors.
#> class(y)
#[1] "matrix"
name <- c("John Smith", "John Doe", "Mary Johnson")
row.names(y) <- name
# treatmenta treatmentb
# John Smith 1 2
# John Doe 16 11
# Mary Johnson 3 1
下面有这个矩阵,应用循环将行名称更改为数字。
这是矩阵:
treatmenta treatmentb
John Smith NA " 2"
John Doe "16" "11"
Mary Johnson " 3" " 1"
和此代码 as.matrix(apply(y, 2, as.numeric))
结果是这样,但我希望行名是人名
treatmenta treatmentb
[1,] NA 2
[2,] 16 11
[3,] 3 1
转换为 data.table 也不起作用。我该怎么做?
这里是重现数据的代码:
name <- c("John Smith", "John Doe", "Mary Johnson")
treatmenta <- c("NA", "16", "3")
treatmentb <- c("2", "11", "1")
y <- data.frame(name, treatmenta, treatmentb)
rownames(y) <- y[,1]
y[,1] <- NULL
我们可以做到
y <- `dimnames<-`(`dim<-`(as.numeric(y), dim(y)), dimnames(y))
y
# treatmenta treatmentb
#John Smith NA 2
#John Doe 16 11
#Mary Johnson 3 1
或者一个紧凑的选项是
class(y) <- "numeric"
数据
y <- structure(c(NA, "16", " 3", " 2", "11", " 1"), .Dim = c(3L, 2L
), .Dimnames = list(c("John Smith", "John Doe", "Mary Johnson"
), c("treatmenta", "treatmentb")))
您正在从更通用的数据形式(数据帧)转向矩阵(具有暗淡属性的向量)。在此 as.matrix 或任何将数据转换为矩阵的基础方法中,最终将调用 vector(x) 这是通用函数,将所有变量设置为字符,或者将所有内容设置为数字,但名称列设置为 NA(取决于关于你如何称呼 as.matrix)。
话虽如此,如果由于某种原因你仍然必须使用矩阵形式,那么使用它以获得更好的可读性:
treatmenta <- c("1", "16", "3")
treatmentb <- c("2", "11", "1")
y[,1] <- as.matrix(sapply(treatmenta, as.numeric))
y[,2] <- as.matrix(sapply(treatmentb, as.numeric))
#now they are not factors.
#> class(y)
#[1] "matrix"
name <- c("John Smith", "John Doe", "Mary Johnson")
row.names(y) <- name
# treatmenta treatmentb
# John Smith 1 2
# John Doe 16 11
# Mary Johnson 3 1