To: Santiago Guallar <sguallar at yahoo.com>
Cc: "r-help at r-project.org" <r-help at r-project.org>
Sent: Sunday, May 6, 2012 2:18 AM
Subject: Re: [R] creating a new column assigning values of other columns
Bahhhh -- far too much work to recreate (and I don't think you sent us
the file "act.lig"): here's a much better route:
Go to the step immediately before you're in trouble and use dput() on
your data. R will print out a nice plaintext representation that we
can copy and paste and reproduce *exactly* without having to do all
that you show below.
Incidentally, your warning message suggests you should be using
ifelse() instead of if.
To compare:
x <- seq(-3, 3)
abs.x.wrong <- if(x < 0) -x else x # Warning message gives some hint
abs.x.right <- ifelse(x < 0, -x, x)
Hope this helps,
Michael
On Sat, May 5, 2012 at 5:09 PM, Santiago Guallar <sguallar at yahoo.com> wrote:
Hello,
I have to create a new column from the values of other columns of a data frame. The new?column (y$n) is created imposing a condition (using a third variable y$h) that assigns the values of two time variables (y$b and y$timepos). Here's the piece of code to get there (using the attached files):
xact <- read.table("act.lig", sep = ',', col.names=c("ok","time","secs","act"))
xlig <- read.table("lig.txt", sep = ',', col.names=c("ok","time","secs","lig"))
w<- merge(xact, xlig, by = c("time" ,"secs"), all = TRUE, sort=F)
require(reshape)
z <- cbind(w, colsplit(w$time, split=" ", names=c("date", "clock")))
zh<-cbind(z, colsplit(z$clock, split=":", names=c("h","m","s")))
zhd<- cbind(zh, colsplit(zh$date, split="/", names=c("d","mo","y")))
night <- subset(zhd, zh$lig<6 & zhd$h<9 | zh$lig<6 & zhd$h>21)
night$timepos<-as.POSIXct(night$time, tz="GMT", format="%d/%m/%y %H:%M:%S")
a=night$timepos - as.difftime( 1, units="days" )
nighta<-cbind(night,a)
y<- cbind(nighta, b=as.character(a, tz= "GMT", format= "%Y-%m-%d"))
y$n<-with(y, if (h>=0 & h<9) {b} else {timepos}) ## Missing warnings
????????????????????????????????????????????????????????????????????????????In if (h >= 0 & h < 9) { :
????????????????????????????????????????????????????????????????????????????condition has length > 1 and only the first element will be used
How can I go around this problem and get the new column?
Thank you,
Santi