Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply a function to each row in a data frame in R [duplicate]

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 
like image 527
highBandWidth Avatar asked Mar 16 '11 18:03

highBandWidth


People also ask

How do you apply a function to every row of a Dataframe in R?

You can use the apply() function to apply a function to each row in a matrix or data frame in R.

How do I duplicate every row in R?

In R, the easiest way to repeat rows is with the REP() function. This function selects one or more observations from a data frame and creates one or more copies of them.

How do I apply a function to each column in a Dataframe in R?

Apply any function to all R data frame You can set the MARGIN argument to c(1, 2) or, equivalently, to 1:2 to apply the function to each value of the data frame. If you set MARGIN = c(2, 1) instead of c(1, 2) the output will be the same matrix but transposed. The output is of class “matrix” instead of “data.

How do I apply the same function to all rows and columns of a matrix in R?

One of the most famous and most used features of R is the *apply() family of functions, such as apply() , tapply() , and lapply() . Here, we'll look at apply() , which instructs R to call a user-specified function on each of the rows or each of the columns of a matrix.


1 Answers

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 
like image 55
Leo Alekseyev Avatar answered Sep 28 '22 11:09

Leo Alekseyev