【问题标题】:R - check column index with commas in rR - 在 r 中用逗号检查列索引
【发布时间】:2016-03-07 13:50:05
【问题描述】:

我想检查我从外部加载的数据框,如果我发现 commas 而不是 dots,我想替换它(简单),但还要说明我在哪一列找到逗号(这就是我不知道该怎么做)

所以我从类似的东西开始(当然我要检查的列不止两列)

dat <- read.table("data.csv", header=TRUE, sep=";", dec=".")

#    d1  d2
# 1 0.1 0,2
# 2 0.2 0,4
# 3 0.4 0,3
# 4 0.6 0,1
# 5 0.7 0,5

for (col in colnames(dat)) {
  if (dat[,col].....) { # here the missing control
    dat[,col] <- as.numeric(gsub(",", ".", data[,col]))
    warnings(sprintf("Replaced commas by dots in column %s", col))
  }
}

【问题讨论】:

  • if (any(grepl(",", dat[,col])) ) 将在迭代中检查当前列中的逗号。

标签: regex r parsing warnings gsub


【解决方案1】:

我们可以使用lapply 循环遍历列并检查其中是否包含","

lapply(dat, function(x) any(grepl(",", x)))
#    $d1
#[1] FALSE
#
#$d2
#[1] TRUE

【讨论】:

  • colSums(sapply(dat, grepl, pattern = ",", fixed = TRUE)) &gt; 0
  • 非常感谢!!这些是我一直在寻找的,我也可以将它们应用于具有相同结构的进一步检查!
猜你喜欢
  • 1970-01-01
  • 2021-07-23
  • 1970-01-01
  • 1970-01-01
  • 2018-10-31
  • 2021-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多