嗨我有一个字符表,我试图将其转换为数字:
vec1 <- c("B","D","E","NA")
vec2 <- c("B","D","E","NA")
vec3 <- c("B","C","E","NA")
vec4 <- c("B","D","E","NA")
vec5 <- c("B","NA","E","E")
vec6 <- c("B","NA","NA","NA")
mat1 <- (cbind(vec1,vec2,vec3,vec4,vec5,vec6))
mat1
# vec1 vec2 vec3 vec4 vec5 vec6
#[1,] "B" "B" "B" "B" "B" "B"
#[2,] "D" "D" "C" "D" "NA" "NA"
#[3,] "E" "E" "E" "E" "E" "NA"
#[4,] "NA" "NA" "NA" "NA" "E" "NA"
mat1[mat1 == "NA"] <- 0
mat1[mat1 != 0] <- 1
mat1
# vec1 vec2 vec3 vec4 vec5 vec6
#[1,] "1" "1" "1" "1" "1" "1"
#[2,] "1" "1" "1" "1" "0" "0"
#[3,] "1" "1" "1" "1" "1" "0"
#[4,] "0" "0" "0" "0" "1" "0"
mat2
# vec1 vec2 vec3 vec4 vec5 vec6
#[1,] 2 2 2 2 2 2
#[2,] 2 2 2 2 1 1
#[3,] 2 2 2 2 2 1
#[4,] 1 1 1 1 2 1
mat2 <- sapply(as.data.frame(mat1), as.numeric)
这可以使用,即我可以从所有值中减去1以得到原始的引用值,但是如何将引用的值更改为数值?
谢谢,
马特
答案 0 :(得分:2)
尽管@ Vlo不满(并且赋值箭头的方向不正确),但是从字符到数字的向量类的更改是相当安全的。他的代码不必要地复杂,因为矩阵属于character
类,而不是factor
,因此转换为data.frame然后需要使用as.character
是不必要的。 R矩阵不能是因子,因为矩阵不应该具有除dim
向量和dimname-lists(以及携带其自己的类的“核心”原子向量)之外的任何属性。有一个class<-
函数:
class(mat1) <- "numeric" # See the help page: ?`class<-`
它也适用于符合逻辑的角色:
> m <- matrix( c('TRUE','FALSE'), 4,4)
> class(m) <- 'logical' # assignment of `as.logical` to `m[]` fails.
> m
[,1] [,2] [,3] [,4]
[1,] TRUE TRUE TRUE TRUE
[2,] FALSE FALSE FALSE FALSE
[3,] TRUE TRUE TRUE TRUE
[4,] FALSE FALSE FALSE FALSE
如果您想使用apply函数,这将成功:
> mat2 <- apply(mat1,2, function(x) as.numeric(x) )
> mat2
vec1 vec2 vec3 vec4 vec5 vec6
[1,] 1 1 1 1 1 1
[2,] 1 1 1 1 0 0
[3,] 1 1 1 1 1 0
[4,] 0 0 0 0 1 0