Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does approx return a list rather than a data frame or array?

Tags:

r

It makes no sense to me that approx would return a list, since - if I understand it correctly - the two elements of the list that it returns are guaranteed to be numeric and of equal length. Given that, it would seem to make more sense to return an array or a data frame.

I'm writing some functions using approx, and this makes me thing that I don't fully understand how it works. Is there a situation in which a list is necessary, or better?

like image 820
Drew Steen Avatar asked Oct 11 '12 22:10

Drew Steen


People also ask

What is the difference between list and DataFrame in R?

Lists can have components of the same type or mode, or components of different types or modes. They can hence combine different components (numeric, logical…) in a single object. A Data frame is simply a List of a specified class called “data.

Can a data frame element be a list?

Data frame columns can contain lists You can also create a data frame having a list as a column using the data. frame function, but with a little tweak. The list column has to be wrapped inside the function I.

Why would you use a data frame over a vector to store your data?

One difference is that if we try to get a single row of the data frame, we get back a data frame with one row, rather than a vector. This is because the row may contain data of different types, and a vector can only hold elements of all the same type. Internally, a data frame is a list of column vectors.

How do I extract a data frame from a list in R?

Therefore, we can use lapply function for this extraction. For example, if we have a list called LIST that store two data frames then column 3 of each data frame can be extracted by using the command lapply(LIST,"[",3).


1 Answers

Functions take pairlists as arguments. Generally lists are used to pass arguments to lattice graphics, which was the dominant high-level graphics environment before ggplot and descendants came along. Lists are also used to pass parameters to control arguments in many functions. In this case you would expect the x and y lengths to be the same, so it could be a dataframe, but there is no particular reason to demand such a structure, and the base functions points and lines will accept named lists and properly allocate them to their argument lists.

(I do not think a matrix could get properly distributed to the x and y arguments of the base plotting routines even of there were row or column names that matched. Matrices are really folded vectors.)

So I think the answer is that passing lists is most consistent with how functional programming is implemented in R.

like image 165
IRTFM Avatar answered Oct 03 '22 07:10

IRTFM