loops - How to sequentially go through every row and then every column in an r data.frame? -


i have survey data came in via google form. google generates spreadsheet of responses, need split data individual responses, human read though interview published on blog or something.

so let's i've got this:

1st question      2nd question      3rd question "response1 q1"    "response1 q2"    "response1 q3" "response2 q1"    "response2 q2"    "response2 q3" "response3 q1"    "response3 q2"    "response3 q3" 

where first row (the column headers) questions, , each row filled responses questions. want produce this:

1st question ------- response1 q1  2nd question ------- response1 q2  3rd question ------- response1 q3 

essentially, each respondent, want make 1 individual file showing question responses in linear fashion.

i've given specifics of problem i'm trying solve in case there's shortcut particular case but, in general, if you've got data.frame in r that, whatever reason, need traverse row-by-row , column-by-column, how 1 accomplish short of writing loops?

assuming data in data frame (with strings, not factors), this:

qdata = structure(list(q1.text = c("1r.text", "2r.text", "3r.text"),      q2.text = c("1r.text", "2r.text", "3r.text"), q3.text = c("1r.text",      "2r.text", "3r.text"), q4.text = c("1r.text", "2r.text",      "3r.text")), .names = c("q1.text", "q2.text", "q3.text",  "q4.text"), class = "data.frame", row.names = c(na, -3l)) 

(next time, share data dput make structure reproducible.)

i go vectorized solution. here, converted matrix , paste column names entries, separated new lines ("\n") , dashes in example.

qdata.m = as.matrix(qdata) # next, take advantage of "recycling" of column names, # pasting them matrix values newline "\n" separator. qdata.m = paste(colnames(qdata.m), "-------", t(qdata.m), sep = "\n") # note matrices used column-wise, transpose t() # make row-wise instead.  # cat putting text file. we'll separate each # element 2 line breaks. cat(qdata.m, sep = "\n\n")  # q1.text # ------- # 1r.text #  # q2.text # ------- # 1r.text #  # q3.text # ------- # 1r.text # etc. 

one of advantages of using cat here can print directly file (or can first open connection sink---see relative pages more details).

in more general case, if need go row-by-row , column-by-column, nested loops. seems your're not using data frame structure @ point, turn vector unlist() in fact, in case, that's easier did above:

qvect = unlist(qdata) # pasting above, order() sort text # (the order step may take more care non-dummy text isn't #  alphabetical) qvect = paste(names(qvect), "--------", qvect, sep = "\n")[order(qvect)] 

then can proceed cat above.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -