julia: Using `vec` function in a notebook - julia

I was working on a notebook that uses the function vec to convert a 1xN matrix to a N-element vector. This happened without issue, and vec is the recommended method for this, see What's the most efficient way to convert a Matrix{T} of size 1*N or N*1 in Julia to a Vector{T}?
However, I switched to another notebook and now doing the same thing now throws an error:
#cell:
vec1 = [1 2 3]
#cell output:
1×3 Matrix{Int64}:
1 2 3
#cell:
vec1 = vec(vec1)
#cell output:
MethodError: objects of type Vector{Int64} are not callable
Use square brackets [] for indexing an Array.
Stacktrace:
[1] top-level scope
# In[97]:1
[2] eval
# ./boot.jl:360 [inlined]
[3] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
# Base ./loading.jl:1094
Oddly enough, doing the same thing on a terminal works fine, just as in the previous notebook:
julia> vec1 = [1 2 3]
1×3 Matrix{Int64}:
1 2 3
julia> vec1 = vec(vec1)
3-element Vector{Int64}:
1
2
3
I'm using julia 1.6.1 on both the notebook and the terminal. Is there some silly mistake I'm missing here? I'm using DelimitedFiles.readdlm to read a vector from disk, so the output is a matrix by default. Thus, the solution is not as simple as switching from [1 2 3] to [1; 2; 3].

Related

What does '[' (left square bracket) do when treated as a function? [duplicate]

I've seen the function lapply used in R to extract elements from matrices that exist in a list of matrices.
E.g. I have a list of 3 (2x2) matrices, and I want to extract element [1,2] from each of those 3 matrices.
The code: list1 = lapply(mylist, '[', 1,2) works just fine. It returns a list with those 3 elements.
I am trying to research what this is exactly doing. Google hasn't helped and using ?'[' in the R help isn't too explanatory. I don't see how '[' is a function in R, so the code is not intuitive.
The square brackets are in fact a function whose first argument is the object being subsetted. Subsequent arguments are the index to that subset.
# For example, if M is a matrix
M[1, 2] # extracts the element at row 1, col 2
# is the same as
`[`(M, 1, 2)
# Try them!
Now, Have a look at the arguments to lapply:
args(lapply)
# function (X, FUN, ...)
Everything represented in those dots gets passed on to the function FUN as arguments.
Thus, when FUN="[", the first argument to "[" is the current element of the list (being iterated over), ie, the object being subsetted. While the subsequent arguments are the indexes to "["
Operators in R are just functions.
These are equivalent:
> x <- list(a=1,b=2)
> x[1]
$a
[1] 1
> `[`(x,1)
$a
[1] 1
The backticks are necessary only to prevent interpretation by the parser (e.g. to tell it it's a function name not to start interpreting the [ prematurely).
Being a function, it follows the same object-oriented rules (in this case, S3) as everything else.
> methods(`[`)
[1] [.acf* [.arrow* [.AsIs [.bibentry* [.cluster* [.data.frame [.data.table*
[8] [.Date [.difftime [.envlist* [.factor [.formula* [.fractions* [.getAnywhere*
[15] [.gList* [.gpar* [.gtable* [.hexmode [.idf* [.indexed* [.insensitive*
[22] [.ITime* [.listof [.noquote [.numeric_version [.octmode [.pdf_doc* [.person*
[29] [.POSIXct [.POSIXlt [.quoted* [.raster* [.roman* [.shingle* [.simple.list
[36] [.split* [.terms* [.trellis* [.ts* [.tskernel* [.uneval* [.unit*
[43] [.unit.arithmetic* [.unit.list* [.vpPath*
Non-visible functions are asterisked
+, =, etc. and other operators all work this way as well.

Use of lapply after splitting a string in R [duplicate]

I've seen the function lapply used in R to extract elements from matrices that exist in a list of matrices.
E.g. I have a list of 3 (2x2) matrices, and I want to extract element [1,2] from each of those 3 matrices.
The code: list1 = lapply(mylist, '[', 1,2) works just fine. It returns a list with those 3 elements.
I am trying to research what this is exactly doing. Google hasn't helped and using ?'[' in the R help isn't too explanatory. I don't see how '[' is a function in R, so the code is not intuitive.
The square brackets are in fact a function whose first argument is the object being subsetted. Subsequent arguments are the index to that subset.
# For example, if M is a matrix
M[1, 2] # extracts the element at row 1, col 2
# is the same as
`[`(M, 1, 2)
# Try them!
Now, Have a look at the arguments to lapply:
args(lapply)
# function (X, FUN, ...)
Everything represented in those dots gets passed on to the function FUN as arguments.
Thus, when FUN="[", the first argument to "[" is the current element of the list (being iterated over), ie, the object being subsetted. While the subsequent arguments are the indexes to "["
Operators in R are just functions.
These are equivalent:
> x <- list(a=1,b=2)
> x[1]
$a
[1] 1
> `[`(x,1)
$a
[1] 1
The backticks are necessary only to prevent interpretation by the parser (e.g. to tell it it's a function name not to start interpreting the [ prematurely).
Being a function, it follows the same object-oriented rules (in this case, S3) as everything else.
> methods(`[`)
[1] [.acf* [.arrow* [.AsIs [.bibentry* [.cluster* [.data.frame [.data.table*
[8] [.Date [.difftime [.envlist* [.factor [.formula* [.fractions* [.getAnywhere*
[15] [.gList* [.gpar* [.gtable* [.hexmode [.idf* [.indexed* [.insensitive*
[22] [.ITime* [.listof [.noquote [.numeric_version [.octmode [.pdf_doc* [.person*
[29] [.POSIXct [.POSIXlt [.quoted* [.raster* [.roman* [.shingle* [.simple.list
[36] [.split* [.terms* [.trellis* [.ts* [.tskernel* [.uneval* [.unit*
[43] [.unit.arithmetic* [.unit.list* [.vpPath*
Non-visible functions are asterisked
+, =, etc. and other operators all work this way as well.

Raise to power in R

This is a beginner's question.
What's the difference between ^ and **?
For example:
2 ^ 10
[1] 1024
2 ** 10
[1] 1024
Is there a function such as power(x,y)?
1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math?Arithmetic
2: Yes: But you already know it:
`^`(x,y)
#[1] 1024
In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math.
Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply and sapply:
> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4

R Error in x$ed : $ operator is invalid for atomic vectors

Here is my code:
x<-c(1,2)
x
names(x)<- c("bob","ed")
x$ed
Why do I get the following error?
Error in x$ed : $ operator is invalid for atomic vectors
From the help file about $ (See ?"$") you can read:
$ is only valid for recursive objects, and is only discussed in the section below on recursive objects.
Now, let's check whether x is recursive
> is.recursive(x)
[1] FALSE
A recursive object has a list-like structure. A vector is not recursive, it is an atomic object instead, let's check
> is.atomic(x)
[1] TRUE
Therefore you get an error when applying $ to a vector (non-recursive object), use [ instead:
> x["ed"]
ed
2
You can also use getElement
> getElement(x, "ed")
[1] 2
The reason you are getting this error is that you have a vector.
If you want to use the $ operator, you simply need to convert it to a data.frame. But since you only have one row in this particular case, you would also need to transpose it; otherwise bob and ed will become your row names instead of your column names which is what I think you want.
x <- c(1, 2)
x
names(x) <- c("bob", "ed")
x <- as.data.frame(t(x))
x$ed
[1] 2
Because $ does not work on atomic vectors. Use [ or [[ instead. From the help file for $:
The default methods work somewhat differently for atomic vectors, matrices/arrays and for recursive (list-like, see is.recursive) objects. $ is only valid for recursive objects, and is only discussed in the section below on recursive objects.
x[["ed"]] will work.
Here x is a vector.
You need to convert it into a dataframe for using $ operator.
x <- as.data.frame(x)
will work for you.
x<-c(1,2)
names(x)<- c("bob","ed")
x <- as.data.frame(x)
will give you output of x as:
bob 1
ed 2
And, will give you output of x$ed as:
NULL
If you want bob and ed as column names then you need to transpose the dataframe like x <- as.data.frame(t(x))
So your code becomes
x<-c(1,2)
x
names(x)<- c("bob","ed")
x$ed
x <- as.data.frame(t(x))
Now the output of x$ed is:
[1] 2
You get this error, despite everything being in line, because of a conflict caused by one of the packages that are currently loaded in your R environment.
So, to solve this issue, detach all the packages that are not needed from the R environment. For example, when I had the same issue, I did the following:
detach(package:neuralnet)
bottom line: detach all the libraries no longer needed for execution... and the problem will be solved.
This solution worked for me
data<- transform(data, ColonName =as.integer(ColonName))
Atomic collections are accessible by $
Recursive collections are not. Rather the [[ ]] is used
Browse[1]> is.atomic(list())
[1] FALSE
Browse[1]> is.atomic(data.frame())
[1] FALSE
Browse[1]> is.atomic(class(list(foo="bar")))
[1] TRUE
Browse[1]> is.atomic(c(" lang "))
[1] TRUE
R can be funny sometimes
a = list(1,2,3)
b = data.frame(a)
d = rbind("?",c(b))
e = exp(1)
f = list(d)
print(data.frame(c(list(f,e))))
X1 X2 X3 X2.71828182845905
1 ? ? ? 2.718282
2 1 2 3 2.718282

How do I use `[` correctly with (l|s)apply to select a specific column from a list of matrices?

Consider the following situation where I have a list of n matrices (this is just dummy data in the example below) in the object myList
mat <- matrix(1:12, ncol = 3)
myList <- list(mat1 = mat, mat2 = mat, mat3 = mat, mat4 = mat)
I want to select a specific column from each of the matrices and do something with it. This will get me the first column of each matrix and return it as a matrix (lapply() would give me a list either is fine).
sapply(myList, function(x) x[, 1])
What I can't seem able to do is use [ directly as a function in my sapply() or lapply() incantations. ?'[' tells me that I need to supply argument j as the column identifier. So what am I doing wrong that this does't work?
> lapply(myList, `[`, j = 1)
$mat1
[1] 1
$mat2
[1] 1
$mat3
[1] 1
$mat4
[1] 1
Where I would expect this:
$mat1
[1] 1 2 3 4
$mat2
[1] 1 2 3 4
$mat3
[1] 1 2 3 4
$mat4
[1] 1 2 3 4
I suspect I am getting the wrong [ method but I can't work out why? Thoughts?
I think you are getting the 1 argument form of [. If you do lapply(myList, `[`, i =, j = 1) it works.
After two pints of Britain's finest ale and a bit of cogitation, I realise that this version will work:
lapply(myList, `[`, , 1)
i.e. don't name anything and treat it like I had done mat[ ,1]. Still don't grep why naming j doesn't work...
...actually, having read ?'[' more closely, I notice the following section:
Argument matching:
Note that these operations do not match their index arguments in
the standard way: argument names are ignored and positional
matching only is used. So ‘m[j=2,i=1]’ is equivalent to ‘m[2,1]’
and *not* to ‘m[1,2]’.
And that explains my quandary above. Yeah for actually reading the documentation.
It's because [ is a .Primitive function. It has no j argument. And there is no [.matrix method.
> `[`
.Primitive("[")
> args(`[`)
NULL
> methods(`[`)
[1] [.acf* [.AsIs [.bibentry* [.data.frame
[5] [.Date [.difftime [.factor [.formula*
[9] [.getAnywhere* [.hexmode [.listof [.noquote
[13] [.numeric_version [.octmode [.person* [.POSIXct
[17] [.POSIXlt [.raster* [.roman* [.SavedPlots*
[21] [.simple.list [.terms* [.ts* [.tskernel*
Though this really just begs the question of how [ is being dispatched on matrix objects...

Resources