【问题标题】:convert a char to num R将 char 转换为 num R
【发布时间】:2021-07-23 11:01:10
【问题描述】:

我有这个数据

  names(tcars) <- c("MPG",

  "DISPLACEMENT","HORSEPOWER","WEIGHT","ACCELERATION")
     str(tcars) 'data.frame':   38 obs. of  5 variables:  $ MPG         : chr  "16,9" "15,5" "19,2" "18,5" ...  $ DISPLACEMENT: int  350 351 267
  360 98 134 119 105 131 163 ...  $ HORSEPOWER  : int  155 142 125 150
  68 95 97 75 103 125 ...  $ WEIGHT      : chr  "4,36" "4,054" "3,605"
  "3,94" ...  $ ACCELERATION: chr  "2,73" "2,26" "2,56" "2,45" ...

我尝试通过以下请求将 MPG 列转换为数字并收到以下消息

  MPG <- as.numeric(tcars$MPG) NAs introduits lors de la conversion automatique and the type was not converted
  str(tcars) 'data.frame':  38 obs. of  5 variables:  $ MPG         : chr  "16,9" "15,5" "19,2" "18,5" ...  $ DISPLACEMENT: int  350 351 267
  360 98 134 119 105 131 163 ...  $ HORSEPOWER  : int  155 142 125 150
  68 95 97 75 103 125 ...  $ WEIGHT      : chr  "4,36" "4,054" "3,605"
  "3,94" ...  $ ACCELERATION: chr  "2,73" "2,26" "2,56" "2,45" ...

所以我尝试了这段代码,我的数据的所有字符类型都更改为 NA :(

  tcars[] <- lapply(tcars, function(x) as.numeric(as.character(x))) NAs introduits lors de la conversion automatiqueNAs introduits lors de la conversion automatique NAs introduits lors de la conversion automatique

  str(tcars$MPG)  num [1:38] NA NA NA NA 30 NA NA NA NA 17 ...
  data.frame(tcars$MPG)
  data.frame(tcars$DISPLACEMENT)

  str(tcars) 'data.frame':  38 obs. of  5 variables: 
  $ MPG         : num  NA NA NA NA 30 NA NA NA NA 17 ...  $ DISPLACEMENT: num  350 351   267 360 98 134 119 105 131 163 ...  $ HORSEPOWER  : num  155 142 125    150 68 95 97 75 103 125 ...  $ WEIGHT      : num  NA NA NA NA NA NA NA NA NA NA ...  $ ACCELERATION: num  NA NA NA NA NA NA NA NA NA NA ...

【问题讨论】:

  • 请在粘贴代码前使用dput添加数据并删除&gt;
  • 使用 dput 展示你的例子
  • 您是否使用逗号 (,) 作为十进制? 2,73 实际上是 2.73 吗?

标签: r dataframe type-conversion


【解决方案1】:

在将数据转换为数字之前替换逗号。

tcars[] <- lapply(tcars, function(x) as.numeric(sub(',', '.', x)))
tcars

#   MPG HORSEPOWER WEIGHT
#1 16.9        155  4.360
#2 15.5        142  4.054
#3 19.2        125  3.605
#4 18.5        150  3.566

这是假设像 "16,9""15,5" 这样的数字实际上分别是 16.9 和 15.5。

数据

tcars <- data.frame(MPG = c("16,9", "15,5", "19,2", "18,5"), 
                    HORSEPOWER = c(155, 142, 125, 150), 
                    WEIGHT = c("4,36", "4,054", "3,605", "3,566"))

【讨论】:

    【解决方案2】:

    dplyrsolution:

    tcars %>%
      mutate(across(everything(), ~as.numeric(sub(",", ".", .))))
    

    【讨论】:

      猜你喜欢
      • 2012-07-23
      • 1970-01-01
      • 2022-11-18
      • 1970-01-01
      • 1970-01-01
      • 2021-04-29
      • 2013-10-18
      • 2012-01-15
      • 2020-11-25
      相关资源
      最近更新 更多