【问题标题】:Change a char value in a data column into zero?将数据列中的 char 值更改为零?
【发布时间】:2022-01-11 05:03:27
【问题描述】:

我有一个简单的问题,我有一个很长的数据框,它在数据框列中将 0 报告为 char“无”。如何将所有这些替换为数字 0。示例数据框如下

Group Candy
A 5
B nothing

这就是我想把它改成的样子

Group Candy
A 5
B 0

请记住,我的实际数据集是 100 行长。

我自己的尝试是使用 is.na,但显然它只适用于 NA,并且可以轻松地将它们转换为零,但不确定是否有针对实际字符数据类型的解决方案。

谢谢

【问题讨论】:

  • 试试df1$Candy[df1$Candy == "nothing"] <- '0'

标签: r dataframe


【解决方案1】:

最好的方法是读取正确的数据,而不是使用"nothing" 读取缺失值。这可以通过函数read.tableread.csv 的参数na.strings 来完成。然后将NA 更改为零。

对于大型 data.frames,以下函数可能会很慢,但会将 "nothing" 值替换为零。

nothing_zero <- function(x){
  tc <- textConnection("nothing", "w")
  sink(tc)   # divert output to tc connection
  print(x)   # print in string "nothing" instead of console
  sink()     # set the output back to console
  close(tc)  # close connection
  tc <- textConnection(nothing, "r")
  y <- read.table(tc, na.strings = "nothing", header = TRUE)
  close(tc)  # close connection
  y[is.na(y)] <- 0
  y
}

nothing_zero(df1)
#  Group Candy
#1     A     5
#2     B     0

主要优点是将数字数据读取为数字。

str(nothing_zero(df1))
#'data.frame':  2 obs. of  2 variables:
# $ Group: chr  "A" "B"
# $ Candy: num  5 0

数据

df1 <- read.table(text = "
Group   Candy
A   5
B   nothing", header = TRUE)

【讨论】:

    【解决方案2】:
    sapply(df,function(x) {x <- gsub("nothing",0,x)})
    

    输出

         a  
    [1,] "0"
    [2,] "5"
    [3,] "6"
    [4,] "0"
    

    数据

    df <- structure(list(a = c("nothing", "5", "6", "nothing")),
                    class = "data.frame",
                    row.names = c(NA,-4L))
    

    另一种选择

    df[] <- lapply(df, gsub, pattern = "nothing", replacement = "0", fixed = TRUE)
    

    如果你只想申请一栏

    library(tidyverse)
    
    df$a <- str_replace(df$a,"nothing","0")
    

    或应用于基础 R 中的一列

    df$a <- gsub("nothing","0",df$a)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 2020-07-29
      • 1970-01-01
      • 2018-09-09
      • 2020-10-18
      相关资源
      最近更新 更多