공백 채우기

Sangbuem Cho·2023년 3월 25일
0

R

목록 보기
2/3

중간에 공백이 있는 데이터를 위의 내용으로 채우기

sampleData:
https://raw.githubusercontent.com/SangbuemCho/animalStatisticsDS/main/sampleDat.txt

패키지, 데이터 불러오기

library(tidyverse)
url <- "https://raw.githubusercontent.com/SangbuemCho/animalStatisticsDS/main/sampleDat.txt"
df <- read.table(url, header = T)
head(df, 10)

연도가 있는 행번호 확인 및 년도 컬럼 잘라내기

yearList <- which(is.na(df[, 1]) == FALSE)
X = df[, 1]

! 주의

만약 불러온 데이터가 tibble 형태라면 아래와 같이 년도 컬럼 작성을 수정해야 함

X = df[, 1][[1]]

함수작성

foo <- function(x){
  a <- max(which((yearList <= x) == TRUE))
  year = X[yearList[a]]
  return(year)
}

공백을 년도로 채우기

lapply(1:nrow(df), foo) %>% unlist() -> m
df$year2 = m
head(df, 10)
profile
data scientist

0개의 댓글