Rowname And Column Output From A Data Frame
1
0
Entering edit mode
11.2 years ago
robjohn7000 ▴ 110

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

r microarray • 4.3k views
ADD COMMENT
1
Entering edit mode
11.2 years ago

This would seem to be an easier way to do things. I saved your example file as "blah.txt" and made it tab separated.

d <- read.table("blah.txt", header=T, row.names=1)
#This would just give output1
#cat(sprintf("row %s: %i", row.names(d), d$M1), sep="\n")
#This would give output2
#cat(sprintf("row %s: %4.2f", row.names(d), d$M11/d$M1), sep="\n")
#This will give both, with the rows properly interleaved
cat(sprintf("row %s: %i\nrow %s: %4.2f", row.names(d), d$M1, row.names(d), d$M11/d$M1), sep="\n")

You can modify the sprintf() bit to do pretty much whatever you want. Try to avoid for loops in R, they're super slow.

ADD COMMENT
0
Entering edit mode

Thanks dpryan. It worked nicely! I was amazed at how I did not need the for loop. Is this due to cat()?

ADD REPLY
0
Entering edit mode

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).

ADD REPLY
0
Entering edit mode

Thanks again dpryan79

ADD REPLY

Login before adding your answer.

Traffic: 1636 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6