[R] while loop until end of file
Joshua Wiley
jwiley.psych at gmail.com
Mon Aug 30 06:30:21 CEST 2010
Hi Marcel,
Not quite sure what you want the while loop for. Does this do what you want?
mydat <- read.table(textConnection("
Pair group param1
1 D 10
1 D 10
1 R 10
1 D 10
2 D 10
2 D 10
2 D 10
2 R 10
2 R 10"), header = TRUE)
closeAllConnections()
mydat$Pair <- factor(mydat$Pair)
# Calculate the mean of param1 for each level of group AND of Pair
by(mydat$param1, list(mydat$group, mydat$Pair), mean)
# Since there are two means for each Pair, set ncol = 2 and byrow = TRUE
# That way each row in the matrix represents 1 Pair
mydat2 <- matrix(by(mydat$param1, list(mydat$group, mydat$Pair), mean),
ncol = 2, byrow = TRUE)
mydat2 <- cbind(mydat2, mydat2[ , 2] - mydat2[ , 1])
colnames(mydat2) <- c("AveParamD", "AveParamR", "diff")
mydat2
Cheers,
Josh
On Sun, Aug 29, 2010 at 9:08 PM, Marcel Curlin
<cemarcel at u.washington.edu> wrote:
>
> Hi Guys,
> stumped by a simple problem. I would like to take a file of the form
>
> Pair group param1
> 1 D 10
> 1 D 10
> 1 R 10
> 1 D 10
> 2 D 10
> 2 D 10
> 2 D 10
> 2 R 10
> 2 R 10
> etc..
>
> and for each pair, calculate the average of param1 for group D entries,
> subtract from the average of param1 for the group R entries, and then write
> the results (ie, AveParam1D AveParam1R dif) in a tab delimited file. Below
> is the start of my code. the difficulty i am having is in creating a while
> loop that stops once there are no more lines to read from the input file.
> also not sure of the best way to write in the results, though I think I
> should use rbind.
>
> data <- data.frame(alldata)
>
> i <- 1
> # need appropriate while loop
> {
> ss <- subset(data, Pair==i)
> ssD <- subset(ss, DR==D)
> ssR <- subset(ss, DR==R)
> p1 <- mean(ssD$Length)
> p2 <- mean(ssR$Length)
> dif <- p1-p2
> out <- rbind(data.frame(P1, P2, diff)
> i <-i + 1
> }
>
> write.table(out, file="out", quote=F, row.names=F, col.names=T, sep="\t")
>
> I have spent an absurd amount of time trying to sort this out with the
> manual and forum searches. Any suggestions appreciated.
>
> Marcel
>
> --
> View this message in context: http://r.789695.n4.nabble.com/while-loop-until-end-of-file-tp2399544p2399544.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
--
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/
More information about the R-help
mailing list