简体   繁体   中英

R - check column index with commas in r

I'd like to make a check of a data frame that I load from outside and in case I found commas instead dots , I'd like to replace it (easy) but also say in which column I found commas (that's what I don't know how to do)

So I started with something like (of course I'd have much more than two columns to be cheked)

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))
  }
}

We could use lapply to loop over the columns and check if any of them contain "," .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM