[R] newbie help: simple operations in R

Wacek Kusnierczyk Waclaw.Marcin.Kusnierczyk at idi.ntnu.no
Tue Jun 2 15:21:38 CEST 2009


Carletto Rossi wrote:
> I'm sorry but i verify that Simon solution doesn't work. It makes only the
> product between the corrispondent element of the columns (first with first,
> second with seconds, etc,...)
> These are the list of R commands:
>
>   
>> quattro <- read.csv('new_data.csv', header=TRUE)
>> names(quattro)<-c("x","y")
>> x<-c(NA,quattro$x)
>> y<-c(quattro$y,NA)
>> quattro$t<-quattro$x*quattro$y
>> write.table(quattro,file="with_t.csv",sep="")
>>     
>
>   

you have 2 columns of n values each.  if you multiply each of the n
values in one column with the value from the other column residing in
the next row, the last value in the first column is multiplied by a
non-available value (the non-existent n+1 th entry), and the first value
in the second column is not used.  is this what you want?  then this
should work:

    result = first * c(second[-1], NA)

or alternatively

    result = (c(NA, first) * c(second, NA))[-1]

if you do just

    result = c(NA, first) * c(second, NA)

then length(result) == n+1

if you use the above

    x<-c(NA,quattro$x)
    y<-c(quattro$y,NA)
    quattro$t<-quattro$x*quattro$y

you effectively compute row products without the shift, because you use
the original columns, ignoring the x and y created one step earlier.

vQ




More information about the R-help mailing list