I have been trying to remove the line breaks from a data set in R. All the columns are factors hence before i could replace the "\n" with "NA", i need to change the data type from factor to character or Date. I am mentioning my code and a sample data set for a better understanding:
sku Stockout_start Stockout_End create_date
0BX-164463 \N 1/29/2015 11:35 1/29/2015 11:35
0BX-164463 2/11/2015 18:01 \N 2/11/2015 18:01
0BX-164464 \N 1/29/2015 11:38 1/29/2015 11:38
0BX-164464 1/30/2015 4:38 \N 1/30/2015 4:38
0BX-164481 \N 1/28/2015 9:58 1/28/2015 9:58
0BX-164482 \N 1/29/2015 11:37 1/29/2015 11:37
0BX-164482 2/4/2015 7:17 \N 2/4/2015 7:17
0BX-164483 \N 1/29/2015 11:37 1/29/2015 11:37
0BX-164483 2/7/2015 4:37 \N 2/7/2015 4:37
0BX-164496 \N 1/29/2015 9:45 1/29/2015 9:45
0BX-164497 \N 1/28/2015 10:02 1/28/2015 10:02
0BX-164498 \N 1/29/2015 9:45 1/29/2015 9:45
0BX-164499 \N 1/29/2015 11:36 1/29/2015 11:36
0BX-164500 \N 1/29/2015 11:36 1/29/2015 11:36
0BX-164501 \N 1/29/2015 11:36 1/29/2015 11:36
I have been using below mentioned codes to correct the data:
stk[,2]<- as.Date(as.character(stk[,2]),format = "%y-%m-%d %H:%M:%S")
stk[,2]<- as.character(as.Date(stk[,2], origin = "1970-01-01"))
But these codes change my column 2 to "NA". Kindly help.
You could specify na.strings
and stringsAsFactors=FALSE
in the read.csv/read.table
. (I changed the delimiter to ,
and saved the input data)
stk <- read.csv('Akash.csv', header=TRUE, stringsAsFactors=FALSE,
sep=",", na.strings="\\N")
head(stk,3)
# sku Stockout_start Stockout_End create_date
#1 0BX-164463 <NA> 1/29/2015 11:35 1/29/2015 11:35
#2 0BX-164463 2/11/2015 18:01 <NA> 2/11/2015 18:01
#3 0BX-164464 <NA> 1/29/2015 11:38 1/29/2015 11:38
If you need to replace multiple columns to "Date" class
stk[-1] <- lapply(stk[-1], as.Date, format='%m/%d/%Y %H:%M')
str(stk)
#'data.frame': 15 obs. of 4 variables:
#$ sku : chr " 0BX-164463" " 0BX-164463" " 0BX-164464" " 0BX-164464" ...
#$ Stockout_start: Date, format: NA "2015-02-11" ...
#$ Stockout_End : Date, format: "2015-01-29" NA ...
#$ create_date : Date, format: "2015-01-29" "2015-02-11" ...