R

Using R to stick Excel columns into individual .txt files

MS Excel is great for sorting out stimuli so that it’s all nice and neat and in one place, like when I’ve organised my millions of EEG trigger codes:

triggercodesexcel

…but some programmes (I’m looking at you here, Presentation) require individual .txt files of each column:

txtfiles

It’s easy enough to just copy the columns, paste them into Notepad, and save as .txt files if you don’t have too many, but to do that every time you make changes is really frustrating.

It’s easy enough to get Matlab to sort this out for you as well, but I’m kind of Matlab-phobic and prefer to use R for everything that needs scripting.

So, here’s a quick and dirty little snippet of code that goes through a spreadsheet and saves the contents of every individual column as a separate .txt file with the title of whatever is in the first row. All you have to do first is save your Excel sheet as a .csv file.

stimuli <- read.csv("ALLthestimuli.csv", 
                    header=TRUE, 
                    na.strings=c("", "NA"), 
                    stringsAsFactors=FALSE)
 
for (i in 1:length(colnames(stimuli))){
    write.table(na.omit(stimuli[[i]]), 
    file = paste(as.character(colnames(stimuli)[i]), ".txt", sep=""), 
    row.names = FALSE, col.names = FALSE, quote = FALSE)
}

It’s messy code, but it does the job just fine and saves lots of time and frustration.

Advertisement
Standard

2 thoughts on “Using R to stick Excel columns into individual .txt files

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s