R 将带引号的数字转换为数字 [英] R Convert quoted numbers to numeric

查看:24
本文介绍了R 将带引号的数字转换为数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符表,我正试图将其转换为数字:

Hi I have a table of characters that I am attempting to convert to numbers as so:

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 以获得原始引用值,但是我如何简单地将引用值更改为数值?

This is OK to work with, i.e. I can subtract 1 from all the values to get to the original quoted values, but how do I simply change the quoted values to numeric values?

谢谢,

马特

推荐答案

尽管 @Vlo 不满意(以及分配箭头的方向不正确),将向量的类从字符更改为数字还是相当安全的.他的代码不必要地复杂,因为矩阵属于 character 类而不是 factor,所以转换为 data.frame 然后需要使用 as.character 是不必要的.R 矩阵不能是因子,因为矩阵不应该具有除 dim 向量和 dimname-lists(以及带有自己的类的核心"原子向量)之外的任何属性.有一个 class<- 函数:

Despite @Vlo's displeasure (and incorrect orientation of the assignment arrow) the change in the class of a vector from character to numeric is fairly safe. His code is needlessly complicated because the matrix was of class character rather than being a factor, so conversion to data.frame and then needing to use as.character was unnecessary. R matrices cannot be factors, since matrices are not supposed to have any attributes other than a dim vector, and dimname-lists (and the "core" atomic vector that carries its own class). There is a class<- function:

 class(mat1) <- "numeric"   # See the help page:  ?`class<-`

它也适用于字符到逻辑:

It also works for character to logical:

> 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

如果你想使用应用函数,这会成功:

If you wanted to use an apply function, this would succeed:

> 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

这篇关于R 将带引号的数字转换为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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