Skip to content
Prev 313969 / 398506 Next

"For" loop and "if" question

HI,
You could replace the times=..... in res1 with:
res1<-na.omit(cbind(ID=rep(dat2[,2][grep("ID",dat2$variable)],times=length(grep("p",names(dat1)))),dat2[grep("p",dat2$variable),],dat2[grep("lat",dat2$variable),],dat2[grep("long",dat2$variable),]))

A.K.


----- Original Message -----
From: arun <smartpink111 at yahoo.com>
To: Steven Ranney <steven.ranney at gmail.com>
Cc: R help <r-help at r-project.org>
Sent: Wednesday, December 19, 2012 11:38 PM
Subject: Re: [R] "For" loop and "if" question



Hi,
You could also try this:
#dat1<-structure.... BTW, p20 was labelled incorrectly as p29
library(reshape)
?dat2<-melt(dat1)
res1<-na.omit(cbind(ID=rep(dat2[,2][grep("ID",dat2$variable)],times=((nrow(melt(dat1))-nrow(dat1))/3)/nrow(dat1)
),dat2[grep("p",dat2$variable),],dat2[grep("lat",dat2$variable),],dat2[grep("long",dat2$variable),]))
res1<-res1[,-c(3,4,6)]
?res1[,2]<-as.numeric(gsub("\\D+","",res1[,2]))
?colnames(res1)[2:4]<-c("p","lat","long")
?row.names(res1)<-1:nrow(res1)
?head(res1)
#??? ID p????? lat????? long
#1 2004 1 29.26600 -89.96268
#2 2005 1 29.27057 -89.95791
#3 2006 1 29.24012 -90.00651
#4 2007 1 29.22798 -90.02192
#5 2008 2 29.27332 -89.95430
#6 2006 4 29.23984 -90.00668
identical(res1[,-1],fun(dat1))
#[1] TRUE

A.K.






----- Original Message -----
From: Rui Barradas <ruipbarradas at sapo.pt>
To: Steven Ranney <steven.ranney at gmail.com>
Cc: r-help at r-project.org
Sent: Wednesday, December 19, 2012 6:16 PM
Subject: Re: [R] "For" loop and "if" question

Hello,

Thanks for the data example.
Try the following.


fun <- function(DF){
? ?? f <- function(x, y){
? ? ? ?? if(ncol(y) == 3) rbind(x, y) else x
? ?? }

? ?? p <- grep("^p[[:digit:]]+$", names(DF))
? ?? lat <- grep("^lat[[:digit:]]+$", names(DF))
? ?? long <- grep("^long[[:digit:]]+$", names(DF))
? ?? p <- sapply(DF[p], as.logical)
? ?? lat <- sapply(DF[lat], as.numeric)
? ?? long <- sapply(DF[long], as.numeric)

? ?? tmp <- sapply(seq_len(ncol(p)), function(j)
? ? ? ?? cbind(p = j, lat = lat[p[, j], j], long = long[p[, j], j]))
? ?? tmp <- na.omit(Reduce(f, tmp))
? ?? data.frame(tmp, row.names = seq_len(nrow(tmp)))
}

fun(dat)? # 'dat' is your data example, dat <- structure(...)


Hope this helps,

Rui Barradas
Em 19-12-2012 20:56, Steven Ranney escreveu:
______________________________________________
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.


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