I have the following dataframe:
M1 M6 M7 M8 M9 M10 M11
35 48 48 48 96 96 84 84
37 48 48 48 96 96 84 84
49 63 63 24 87 87 81 81
and I want 2 outputs from the data frame as follows:
output1: row names and the first elements of the first column (M1): e.g., row 35: 48
output2: row names and the result of dividing the elements of row 7 (M11) by the elemnts of row 1 (M1):
e.g., row 35: 0.57
My code:
data <- data.frame(data)
data$id <- rownames(data)
for (i in 1:nrow(data)){
id <- data$id[i]
u <- data[i,1]
x <- data$M11[i]/dataM1[i]
#table(id,u)
#print(table(id,u))
#table(id,x)
cat(sprintf('row %s: %s', id, u))
cat(sprintf('row %s: %s', id, x))
#print(id, u)
}
Using the commentd out "print(table(id,u))" gives the right output but not well formated , but "cat(sprintf('row %s: %s', id, u))" gives R's row index and value for u. Any help to get the code working properly will be appreciated! Thanks
Thanks dpryan. It worked nicely! I was amazed at how I did not need the for loop. Is this due to cat()?
No, just remember that R isn't like C or other languages, where you would need the for loop. 9 times out of 10, you'll find that R's functions will work to process things as a vector and then give output appropriate to that. BTW, without cat(), sprintf() will have a similar behavior, only it well return a character vector rather than printing things in the desired manner (BTW, if you want that printed to a file, the easiest way in R is with the sink() command, so don't bother with fprintf() or anything like that).
Thanks again dpryan79