####
#
# 03A Data import and export
#
####

#
# Working directory
#

getwd()

setwd("C:\\Users\\yourname\\path\\R intro") 

setwd("C:/Users/yourname/path/R intro")

#
# Data import: structured data
#

df <- read.table(	file = "BALIBOMBING2002_2002.csv", 
                  header = TRUE,
                  sep = ",", 
                  row.names = 1, 
                  na.strings = "NA", 
                  stringsAsFactors = FALSE, 
                  fileEncoding = "UTF-8") 

str(df)

#
# Data import: unstructured data
#

text <- readLines(con = "BALIBOMBING2002_2002.csv", 
                  warn = TRUE,
                  encoding = "UTF-8") 

str(text)

#
# Data import: RData files
#

load(file = "balibombing.rdata")

#
# Data conversions
#

?as.matrix()

?as.list()

?as.data.frame()

#
# Data conversions: DF to matrix
#

mat <- as.matrix(df)

str(df)

#
# Data conversions: matrix to DF
#

mat2df <- as.data.frame(mat)

mat2df <- as.data.frame(mat, stringsAsFactors = FALSE)

#
# Names of rows and columns
# 

colnames(df) <- c("var1" , "var2", "var3", "var4", "var5")

colnames(df) <- paste0("actor" , 1:27)

colnames(mat) <- paste0("actor" , 1:27)

colnames(mat) <- rownames(mat)

#
# Data export: saving entire workspace
#

save.image(file = "workspace_2018_07_04.rdata")

#
# Data export: saving particular object as Rdata
#

save(df,
     file = "BALIBOMBING_export.rdata")

#
# Data export: saving tabular data
#

write.table(df, 
            "BALIBOMBING_export.csv",
            sep = ",", 
            row.names = TRUE, 
            col.names = TRUE, 
            fileEncoding = "UTF-8") 

#
# Data export: saving unstructured data
#

writeLines(df, 
           "BALIBOMBING_export.txt")

