【问题标题】:Converting three variables in a dataframe from chr to int in R将数据框中的三个变量从 chr 转换为 R 中的 int
【发布时间】:2020-05-08 16:58:05
【问题描述】:

对 R 非常陌生,但我希望这会很简单。我有一个 html 表,我刮到 R 中,它看起来像这样:

`'data.frame':  238 obs. of  6 variables:
$ Facility Name      : chr  "Affinity Healthcare Center"     "Alameda Care Center" "Alcott Rehabilitation Hospital" "Alden Terrace Convalescent Hospital" ...
$ City               : chr  "Paramount" "Burbank" "Los Angeles" "Los Angeles" ...
$ State              : chr  " CA" " CA" " CA" " CA" ...
$ Confirmed Staff    : chr  "26" "36" "14" "27" ...
$ Confirmed Residents: chr  "29" "49" "26" "85" ...
$ Total Deaths       : chr  26 36 14 27 19 3 1 7 16 3 ...`

我希望 Confirmed StaffConfirmed ResidentsTotal Deaths 是整数,这样我就可以对它们进行一些数学运算并进行排序、排序等。

我对一个变量进行了尝试,它似乎工作正常:

`tbls_ls4$`Total Deaths` <- as.integer(tbls_ls4$`Confirmed Staff`)`

但我想将它应用于所有三个变量,但不知道该怎么做。

【问题讨论】:

  • 拥有factors不是更好吗?
  • lapply(df,as.integer)dplyr::mutate(across(is.character,~as.integer)
  • 请注意,across 仅在 dplyr 的开发版本中可用。
  • @NelsonGon:我在问@jkandel,他/她是否知道factor 变量允许排序/排序等而不会丢失有关标签的信息。我认为,鉴于这个问题,factors 对于前两个变量更好

标签: r integer character


【解决方案1】:

有几种方法可以做到这一点:

library(data.table)
setDT(df)
cols <- c("Confirmed Staff", "Confirmed Residents", "Total Deaths")
df[,cols := lapply(.SD, as.integer),.SDcols = cols]

或者如果你更喜欢基础R

df[, cols] <- lapply(cols, function(d) as.integer(df[,d]))

【讨论】:

    【解决方案2】:

    您还可以使用 tidyverse 包中的 mutate_at 将某些列从字符转换为整数。

    library(tidyverse)
    
    df<-df %>%
      # Indicate the column names you wish to convert inside vars
      mutate_at(vars(ConfirmedStaff,ConfirmedResidents,TotalDeaths),
                # Indicate the function to apply to each column
                as.integer)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-01
      • 2015-12-11
      • 1970-01-01
      • 2022-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-30
      相关资源
      最近更新 更多