29

Possible Duplicate:
how to apply a function to every row of a matrix (or a data frame) in R

R - how to call apply-like function on each row of dataframe with multiple arguments from each row of the df

I want to apply a function to each row in a data frame, however, R applies it to each column by default. How do I force it otherwise?

> a = as.data.frame(list(c(1,2,3),c(10,0,6)),header=T)
> a
  c.1..2..3. c.10..0..6.
1          1          10
2          2           0
3          3           6
> sapply(a,min)
 c.1..2..3. c.10..0..6. 
          1           0 

I wanted something like

1   2
2   0
3   3
Community
  • 1
  • 1
highBandWidth
  • 16,751
  • 20
  • 84
  • 131
  • 1
    I saw lapply doc said it returns a list, and sapply doc said it is a user friendly version that returns an object of the appropriate type. – highBandWidth Mar 16 '11 at 19:09
  • 3
    `lapply()` and `sapply()` operate over the *components* of a vector. That vector can be an atomic vector (e.g. `1:10`) or a list. For a list, it applies the function to each component of the list. A data frame is a special case of a list, where the "columns" are the components, hence `lapply()` and `sapply()` work on the "columns" of a data frame. – Gavin Simpson Mar 16 '11 at 19:15
  • 2
    It doesn't say that; it says, "sapply is a user-friendly version of lapply by default returning a vector or matrix if appropriate." – Joshua Ulrich Mar 16 '11 at 19:15

1 Answers1

40

You want apply (see the docs for it). apply(var,1,fun) will apply to rows, apply(var,2,fun) will apply to columns.

> apply(a,1,min)
[1] 1 0 3
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
Leo Alekseyev
  • 12,893
  • 5
  • 44
  • 44
  • What if I wanted the minimum from a given column? say column 2. – Selvam Oct 20 '12 at 10:39
  • 1
    @Selvam, `min(a[,2])` -- but you should probably read through some of the introductory R material (such as http://cran.r-project.org/doc/manuals/R-intro.html#Array-indexing ) -- that's a pretty basic question. – Ben Bolker Oct 20 '12 at 13:48
  • 26
    This doesn't exactly answer the original questions. `apply()` will try to convert the data.frame into a matrix (see the help docs). If it does not gracefully convert due to mixed data types, I'm not quite sure what would result. – Shea Parkes Jan 17 '13 at 14:58
  • @SheaParkes If you don't need the strings in the function, just do apply(a[NumericColNames],1,min). – jeb Feb 21 '13 at 22:48
  • 2
    @SheaParkes I believe it will convert all data types to the "lowest common denominator", which usually ends up being simply character. – antoine Aug 12 '15 at 20:41