【问题标题】:Convert matrix of chars in ascii code with R用R转换ASCII码中的字符矩阵
【发布时间】:2020-06-09 14:15:20
【问题描述】:

我正在尝试使用 R 编程将我的字符矩阵转换为整数矩阵(使用 ascii 代码)。我尝试了几种方法,我发现这种方法可行,因为当我打印它时,它显示了我想要的。但是它不起作用:

In `[<-.factor`(`*tmp*`, iseq, value = 122L) :
  invalid factor level, NA generated

请帮忙。 这是我的代码:

library("FactoMineR")
library("factoextra")
library(dplyr)
library(readr)
library("gtools")


a <- c('a','t','r','h','f','t','z')
b <- c('v','q','o','h','p','s','z')
mush <- cbind(a,b)

for(i in 1:7){ 
  for(j in 1:2){ 
    data_active[i,j] <- strtoi(asc(toString(mush[i,j])))
    print(strtoi(asc(toString(mush[i,j]))))
  }
}

#res = PCA(data_active, scale.unit = TRUE, ncp = 3, graph = TRUE)
#mush <- read.csv(file = "mushrooms.csv", sep = ",", stringsAsFactors = FALSE)
#data_active <- (mush[1:500, 1:23])

【问题讨论】:

    标签: r matrix char ascii


    【解决方案1】:

    您可以使用utf8ToInt

    mush[] <- sapply(mush, utf8ToInt)
    

    【讨论】:

      【解决方案2】:

      dplyr,我们可以使用

      library(dplyr) # using devel version
      mush <-  mush %>%
                  mutate(across(everything(), utf8ToInt))
      

      或者在当前版本中

      mush <- mush %>%
                  mutate_all(utf8ToInt)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-18
        • 2017-06-14
        • 2014-01-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多