[R] dataframe manipulation

Prof Brian D Ripley ripley at stats.ox.ac.uk
Mon Oct 1 08:59:46 CEST 2001


On Sun, 30 Sep 2001 kestickler at netscape.net wrote:

> Hi,
>
> a couple of questions on manipulating a dataframe:
>
> 1) Without using a for loop (often inefficient, as i understand, in R), is it possible to split a dataframe into a list of dataframes with the number of *columns* in each (child)dataframe specified by the elements of a numeric vector?
> for example:
>
> dataframe
> 10 20 30 40
> 24 90 34 12
> 12 44 67 77
> split using the vector c(3, 1)
> results in 2 dataframes of 3 and 1 column.
> 10 20 30
> 24 90 34
> 12 44 67
>
> and
> 40
> 12
> 77

I would loop over the elements of the split.

sp <- c(3, 1)
csp <- c(0, cumsum(sp))
res <- list(length(split))
for(i in seq(along=sp))
  res[[i]] <- df[(1+csp[i]):csp[i+1]]

There are better ways if you had many subgroups, but not for two.

>
>
> 2) To find the abs() of the difference between every element of a
dataframe and the element in the nth column in the *same row*,
i use the following code:
>
> n <- 4
> apply(df, 1, myDist, df[n,])
> myDist <- function(x, y) {
>     dist <- sum(abs(x-y));
>     return (dist);
> }
>
>
> This however, produces an error message:
> Fails as: Error in abs: non-numeric argument to function
> I guess its because df[n,] creates a dataframe and not a vector. Any suggestions on how to modify the function?

Oops: df[, n] is the nth column, not df[n, ], and that's the error.

Secondly, myDist needs to return a vector argument: you have returned the
sum of the absolute differences, not the absolute differences.

Third, apply takes an array as its argument, not a data frame, so in fact
coerces df to a matrix.

Here is what I think you wanted:

m <- as.matrix(df)
abs(m - m[, n])


BTW, the `;' in myDist are unnecessary: this is not C.

myDist <- function(x, y) sum(abs(x-y))

will do.



-- 
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list