Search code examples
rcallcsv

Loading and writing TSV files with data in R


I am trying to run some tests on real data that I found online. I have downloaded and saved it to my computer in a .tsv file and am trying to call it into R and create a table for it that I can read later and run a some tests on. Here's what I have so far to try to call it in. This also includes recoding some of the variables to eliminate NA or DK answers (which I'm not sure I did correctly):

ais_all <- read.delim("/Users/Jkels/Documents/Introduction to Computational Statistics/33661-0001-Data.tsv",sep="\t",header=TRUE)

ais_small <- data.frame(age=ais_all$AGE, gender=ais_all$SEX, football=ais_all$TSFRFB, tennis=ais_all$TSFRTN, drunk=ais_all$SAI07)

ais_table$SAI07[ais_table$SAI07 < 0] <- 4
ais_table$TSFRFB[ais_table$TSFRFB == 1] <- 0
ais_table$TSFRTN[ais_table$TSFRTN == 1] <- 0
ais_table$SEX[ais_table$SEX < 0] <- NA
ais_table$AGE[ais_table$AGE < 0] <- NA

ais_table <- write.table(ais_small,"/Users/Jkels/Documents/Introduction to Computational Statistics/ais_small.tsv",sep=",",row.names=FALSE)

I'm still fairly new at R and now, I am trying to write and save the table into a file that I can pull later. The file is saving, but when I open the new file, there is no text in there and thus, my later regressions don't work. Any suggestions on how to work around this and get the table to write and organize properly?

Thanks!


Solution

  • load() in R imports .RData files which are native R files comprising of all objects and functions from previous projects.

    read.table() is the most generalized of the family of data frame input functions to import from popular flatfile formats (csv, txt, tab-delimited, etc.) which include the more specific versions:

    • read.csv
    • read.csv2
    • read.delim
    • read.delim2

    All the above input functions use file for the first argument which refers to a string literal (either as a relative or absolute path) and NOT an object.