Skip to content
Prev 79576 / 398502 Next

Any way to add to data frame saved as .rData file?

thx everyone for your help...for simplicity, i elected to stay with a text 
file and transpose it so that each new row of data is really a column...in 
this transposed file, the header is really the row labels. the first cell 
has the name of the row labels ("RowID" in this case)...

here's code for what i ended up doing, in case anyone wants it (or wants to 
improve it) :


outfile <- mydata.txt

zz <- file(outfile, "w")

rowlabels <- c(1:10000)

cat(c("RowID", rowlabels, "\n"), file = zz, sep = "\t")   # make the first 
row of the file have the row labels

grep_text <- function(s)   # 's' is a unique string that is contained in the 
col or cols that you want
{
	temp_header <- scan(file = outfile, what = list("RowID"), flush = TRUE)
	temp_header <- unlist(temp_header)
	g <- grep(toString(s), temp_header)  # gives the row number in outfile with 
the data you want

	if(length(g)==1)
	{
		temp_file <- scan(file = outfile, what = character(), skip = g-1, nlines = 
1)  # temp_file = a vector
		temp_file <- temp_file[2:length(temp_file)]  # drop title
		temp_file <- as.numeric(temp_file)  # now this is num vector
		tf_df <- as.data.frame(temp_file)
	}

	if(length(g)>1)
	{
		for(i in 1:length(g))
		{
			temp_file <- scan(file = outfile, what = character(), skip = g[i]-1, 
nlines = 1)
			temp_file <- temp_file[2:length(temp_file)]  # drop title
			temp_file <- as.numeric(temp_file)  # now this is num vector

			if(i==1)
			{
				tf_df <- as.data.frame(temp_file)
			}

			if(i!=1)
			{
				tf_df[i] <- temp_file
			}
		}
	}

	return(tf_df)
}


you would use grep_text(s) to return a data frame with column titles 
contained in the string s...if i had a column named "Year05_population" in 
the "mydata.txt" file, to return a data frame named 'df' with only that one 
column titles "Year05_population" i would simply type :

outfile <- mydata.txt
df <- grep_text("Year05_population")