d <- read.csv(file = 'https://stats.dip.jp/01_ds/data/data_cleansing2_dirty_data.csv')
m <- as.matrix(d)
boxplot(m)

any(m < 0)
## [1] TRUE
any(abs(m) > 3*sd(m))
## [1] TRUE
jj <- 36:46
boxplot(m[, jj])

# 異常値が入っているカラム(列)の棒グラフを作成
j <- 37
y <- m[, j]
barplot(height = y, # 棒グラフの高さ
names.arg = 1:nrow(m)) # 横軸名

ii <- 140:231
y <- m[ii, j]
barplot(height = y, # 棒グラフの高さ
cex.names = 0.4, # 横軸ラベルの大きさ
names.arg = paste(ii, '\n(', y, ')')) # 横軸名 \nで改行して値も()内に表示

# さらにレコード(行)の範囲を絞り特定する。
ii <- 194:206
y <- m[ii, j]
barplot(height = y, # 棒グラフの高さ
cex.names = 0.4, # 横軸ラベルの大きさ
names.arg = paste(ii, '\n(', y, ')')) # 横軸名 \nで改行して値も表示

m[200, j]
## V37
## -0.78
m[m < 0]
## [1] -21.00 -0.78 -0.99 -0.68
sigma <- sd(m) # 標準偏差
# 4シグマ(標準偏差の4倍)を超える値
m[abs(m) > 4*sigma]
## [1] 22 -21 11
m.a <- NULL # 結果格納用の空のオブジェクトを作成
for (i in 1:nrow(m))
{
for (j in 1:ncol(m))
{
if ( m[i, j] < 0 | m[i, j] > 4*sigma)
{
cat('Row:', i, ', Col:', j, ', Value: ', m[i, j], fill = T)
m.a <- rbind(m.a, t(c(i, j, m[i, j]))) # rbind:行ベクトルを追加
}
}
}
## Row: 39 , Col: 1 , Value: 22
## Row: 52 , Col: 1 , Value: -21
## Row: 91 , Col: 1 , Value: 11
## Row: 200 , Col: 37 , Value: -0.78
## Row: 242 , Col: 100 , Value: -0.68
## Row: 521 , Col: 59 , Value: -0.99
colnames(m.a) <- c('Row', 'Col', 'Value')
m.a
## Row Col Value
## [1,] 39 1 22.00
## [2,] 52 1 -21.00
## [3,] 91 1 11.00
## [4,] 200 37 -0.78
## [5,] 242 100 -0.68
## [6,] 521 59 -0.99