Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the apply function of R confusing rows with columns?

Tags:

r

The following code:

set.seed(0)
m<-matrix(data=runif(6),nrow=2)

apply(m,1,print)
apply(m,1,function(x) print(x) )

gives:

[1] 0.8966972 0.3721239 0.9082078
[1] 0.2655087 0.5728534 0.2016819
          [,1]      [,2]
[1,] 0.8966972 0.2655087
[2,] 0.3721239 0.5728534
[3,] 0.9082078 0.2016819

So, one time print is executed row-wise the other time column-wise. Why that? In my understanding the both calls to apply/print should do exactly the same thing.

like image 236
Funkwecker Avatar asked Apr 20 '17 05:04

Funkwecker


People also ask

How does the apply function work in R?

Apply functions are a family of functions in base R which allow you to repetitively perform an action on multiple chunks of data. An apply function is essentially a loop, but run faster than loops and often require less code.

What is the use of apply family functions in R explain in detail?

The apply() family pertains to the R base package and is populated with functions to manipulate slices of data from matrices, arrays, lists and dataframes in a repetitive way. These functions allow crossing the data in a number of ways and avoid explicit use of loop constructs.

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

In R Programming Language to apply a function to every integer type value in a data frame, we can use lapply function from dplyr package. And if the datatype of values is string then we can use paste() with lapply.


1 Answers

There are two things to distinguish here: what print prints, and what it returns.

The print method for a numeric vector will print the contents of the vector to the screen. This is the first part of the output you got:

[1] 0.8966972 0.3721239 0.9082078
[1] 0.2655087 0.5728534 0.2016819

Here, the first row is the printed output for row 1 of your matrix, and the second row is the printed output for row 2.

In addition to this, the print method is a function, like any other function; it returns a value. The value it returns is (for the default methods) what was passed into it. This returned value is passed back to apply, as a series of vectors. apply then concatenates these vectors into a matrix:

          [,1]      [,2]
[1,] 0.8966972 0.2655087
[2,] 0.3721239 0.5728534
[3,] 0.9082078 0.2016819

Why are the vectors treated as column vectors? Because that's what apply does. From ?apply:

Value

If each call to FUN returns a vector of length n, then apply returns an array of dimension c(n, dim(X)[MARGIN]) if n > 1. If n equals 1, apply returns a vector if MARGIN has length 1 and an array of dimension dim(X)[MARGIN] otherwise.

like image 186
Hong Ooi Avatar answered Nov 15 '22 04:11

Hong Ooi