R - 用r中的逗号检查列索引

时间:2016-03-07 13:50:06

标签: regex r parsing warnings gsub

我想检查一下我从外面加载的数据框,如果我发现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))
  }
}

1 个答案:

答案 0 :(得分:3)

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

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