LoginSignup
0
0

More than 1 year has passed since last update.

R勉強会 第五回 アウトプット用課題 解答例&解説

Last updated at Posted at 2022-07-21

この記事はこちらの記事の解答例&解説です.作成途中です.

第1問

CV <- function(data){
  return(sd(data)/mean(data))
}

第2問

zero_one_scale <- function(vec){
  res <- (vec - min(vec))/(max(vec) - min(vec))
  return(res)
}

第3問

my_cumsum <- function(vec){
  res <- c()
  now <- 0
  for(x in vec){
    now <- now + x
    res <- append(res, now)
  }
  return(res)
}

第4問

test_of_no_correlation <- function(N, r){
  t <- (abs(r)*((N-2)**(1/2)))/((1-r**2)**(1/2))
  p <- 2*pt(t, N-2, lower.tail = FALSE)
  return(p)
}

第5問

extremum_detector <- function(data){
  n_points <- length(data)
  extremum_index <- c()
  for(i in 1:(n_points-4)){
    window <- data[i:(i+4)]
    zougen <- c()
    for(j in 2:5){
      zougen <- append(zougen, window[j] - window[j-1] >= 0)
    }
    if(sum(xor(zougen, c(TRUE, TRUE, FALSE, FALSE))) == 0 | sum(xor(zougen, c(T, T, F, F))) == 4){
      extremum_index <- append(extremum_index, i+2)
    }
  }
  return(extremum_index)
}

第6問

my_kmeans <- function(x, y, k){
  centroids <- list()
  for(c in 1:k){
    centroids <- append(centroids, list(c(sample(1:100,1), sample(1:100,1))))
  }
  now_cls <- rep(1, 50)
  while(1){
    next_cls <- c()
    for(i in 1:50){
      dist <- c()
      for(j in 1:k){
        dist <- append(dist, (centroids[[j]][1] - x[i])**2 + (centroids[[j]][2] - y[i])**2)
      }
      next_cls <- append(next_cls, which.min(dist))
    }
    if(sum(next_cls == now_cls) == 50){
      return(as.character(now_cls))
    }else{
      now_cls <- next_cls
      for(c in 1:k){
        centroids[[c]] <- c(mean(x[now_cls == c]), mean(y[now_cls == c]))
      }
    }
  }
}
0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0