Export variables from Matlab struct to R - r

I think this won't be very complex, but I'm unable to figure this out.
I have in Matlab a 17x1 struct object with 6 fields, named photolist. I only want to export the name field , to use in R.
photolist.name gives me the list I need, but when I want to store it in a variable:
name = photolist.name
I only get the first value, same for
name = getfield(photo_list, 'name')
and while
name = [photolist.name]
gives me all values, it does so in one long string without spaces.
using
save('temp.mat', 'photolist')
gives me something I can import to R, but then I need to go multiple nested layers deep to get the values I need, which is a workaround but not very satisfying.
How do i save just the .name fields to a variable?

Found it, was already answered here
names = extractfield(photolist, 'name')
And another way to get the same result is:
names = {photolist.name}

Related

How do I write a dplyr pipe-friendly function where a new column name is provided from a function argument?

I'm hoping to produce a pipe-friendly function where a user specifies the "name of choice" for a new column produced by the function as one of the function arguments.
In the function below, I'd like name_for_elective to be something that the user can set at will, and afterwards, the user could expect that there will be a new column in their data with the name that they provided here.
I've looked at https://dplyr.tidyverse.org/reference/dplyr_data_masking.html, the mutate() function documentation, searched here, and tried working with https://dplyr.tidyverse.org/reference/rename.html, but to no avail.
elective_open<-function(.data,name_for_elective,course,tiebreaker){
name_for_elective<-rlang::ensym(name_for_elective)
course<-rlang::ensym(course)
tiebreaker<-rlang::ensym(tiebreaker)
.data%>%
mutate(!!name_for_elective =ifelse(!!tiebreaker==max(!!tiebreaker),1,0))%>%mutate(!!name_for_elective=ifelse(!!name_for_elective==0,!!course[!!name_for_elective==1],""))%>%
filter(!(!!course %in% !!name_for_elective))
}
I've included this example function because there are several references to the desired new column name, and I'm unsure if the context in which the reference is made changes syntax.
As you can see, I was hoping !!name_for_elective would let me name our new column, but no. I've played with {{}}, not using rlang::ensym, and still haven't got this figured out.
Any solution would be greatly appreciated.
This: Use dynamic variable names in `dplyr` may be helpful, but I can't seem to figure out how to extend this to work in the case where multiple references are made to the name argument.
Example data, per a good suggestion by #MrFlick, takes the form below:
dat<-tibble(ID=c("AA","BB","AA","BB","AA","BB"),Class=c("A_Class","B_Class","C_Class","D_Class","E_Class","F_Class"),
randomNo=c(.75,.43,.97,.41,.27,.38))
The user could then run something like:
dat2<-dat%>%
elective_open(MyChosenName,Class,randomNo)
A desired result, if using the function a single time, would be:
desired_result_1<-tibble(ID=c("AA","BB","AA","BB"),
Class=c("A_Class","D_Class","E_Class","F_Class"),
randomNo=c(.75,.41,.27,.38),
MyChosenName=c("C_Class","B_Class"))
The goal would be to allow this function to be used again if so desired, with a different name specified.
In the case where a user runs:
dat3<-dat%>%
elective_open(MyChosenName,Class,randomNo)%>%
mutate(Just_Another_One=1)%>%
elective_open(SecondName,Class,randomNo)
The output would be:
desired_result_2<-tibble(ID=c("AA","BB"),
Class=c("E_Class","F_Class"),
randomNo=c(.27,.38),
MyChosenName=c("C_Class","B_Class"),
Just_Another_One=c(1,1),
SecondName=c("A_Class","D_Class"))
In reality, there may be any number of records with the same ID, and any number of Class-es.
In this case you can just stick to using the embrace {{}} option for your variables. If you want to dynamically create column names, you're going to still need to use :=. The difference here is that you can use the glue-style syntax with the embrace operator to get the name of the symbol. This works with the data provided.
elective_open <- function(.data, name_for_elective, course, tiebreaker){
.data%>%
mutate("{{name_for_elective}}" := ifelse({{tiebreaker}}==max({{tiebreaker}}),1,0)) %>%
mutate("{{name_for_elective}}" := ifelse({{name_for_elective}}==0,{{course}}[{{name_for_elective}}==1],"")) %>%
filter(!({{course}} %in% {{name_for_elective}}))
}

How do I use get() in R to access a variable with another variable?

I have a loop which is running over a vector containing names of a few tens of dataframes that are in my environment. On each iteration, I want to access the dataframe using the name, and access a specific column within it. As I understand it, the best way to access a variable with a string is using get().
But when I try and do this (with name being a variable containing the string "first.name"):
get(column.name, name)
I get the error:
Error in as.environment(pos) : no item called "first.name" on the search list
It does work if I try to run:
get(column.name, first.name)
So, assuming that get() is the right function for this, what am I doing wrong?
Reproduceable example:
my.df <- as.data.frame(x = seq(1:10), y = rnorm(10))
name <- "my.df"
get("x",name)
We may need to use
get(name)[[column.name]]

Combining many vectors into one larger vector (in an automated way)

I have a list of identifiers as follows:
url_num <- c('85054655', '85023543', '85001177', '84988480', '84978776', '84952756', '84940316', '84916976', '84901819', '84884081', '84862066', '84848942', '84820189', '84814935', '84808144')
And from each of these I'm creating a unique variable:
for (id in url_num){
assign(paste('test_', id, sep = ""), FUNCTION GOES HERE)
}
This leaves me with my variables which are:
test_8505465, test_85023543, etc, etc
Each of them hold the correct output from the function (I've checked), however my next step is to combine them into one big vector which holds all of these created variables as a seperate element in the vector. This is easy enough via:
c(test_85054655,test_85023543,test_85001177,test_84988480,test_84978776,test_84952756,test_84940316,test_84916976,test_84901819,test_84884081,test_84862066,test_84848942,test_84820189,test_84814935,test_84808144)
However, as I update the original 'url_num' vector with new identifiers, I'd also have to come down to the above chunk and update this too!
Surely there's a more automated way I can setup the above chunk?
Maybe some sort of concat() function in the original for-loop which just adds each created variable straight into an empty vector right then and there?
So far I've just been trying to list all the variable names and somehow get the output to be in an acceptable format to get thrown straight into the c() function.
for (id in url_num){
cat(as.name(paste('test_', id, ",", sep = "")))
}
...which results in:
test_85054655,test_85023543,test_85001177,test_84988480,test_84978776,test_84952756,test_84940316,test_84916976,test_84901819,test_84884081,test_84862066,test_84848942,test_84820189,test_84814935,test_84808144,
This is close to the output I'm looking for but because it's using the cat() function it's essentially a print statement and its output can't really get put anywhere. Not to mention I feel like this method I've attempted is wrong to begin with and there must be something simpler I'm missing.
Thanks in advance for any help you guys can give me!
Troy

Creating (and saving to) an object with a random name

I have a function which I use repeatedly. One of the things it returns is a plot visualising effects of a model. I want the function to save the plot to an object, but I want the name of the object to have a random component to it. I use the function multiple times and don't want the plots to overwrite. But I could use the unique identifier in its name to reference it later for the writeup.
So I tried a few things, trying to save a simple object under a partially-random name. All of them fail because I put a function left from the "<-" sign. I'm not going to give examples, because they are just very very wrong.
So I'd like to have something like:
NAME(randomNumber) <- "some plot"
Which, after running multiple times in a function (with the actual input on the right of course) would result in objects named randomly like
NAME104, NAME314, NAME235, etc.
Is this at all doable?
Yes its doable.
Don't do it.
Make a LIST of objects. You can use the name as the key in the list. Example:
plots = list()
plots[["NAME104"]] = "some plot"
plots[["NAMEXXX"]] = "some other plot"
Why? Because now it's easy to loop over the plots stored in the list. Its also easy to create the list in a loop in the first place, something like:
for(i in 1:100){
data = read.table(paste("data",i,".csv"))
name = data$name[1] # get name from column in file
plots[[name]] = plotthing(data)
}
If you really really want to create a thing with a random name, use assign:
> assign(paste0("NAME",round(runif(1,1,1000))), "hello")
> ls(pattern="NAME*")
[1] "NAME11" "NAME333" "NAME717" "NAME719"
But really DONT do that.

How to use indirect reference to read contents into a data table in R.

How do you use indirect references in R? More specifically, in the following simple read statement, I would like to be able to use a variable name to read inputFile into data table myTable.
myTable <- read.csv(inputFile, sep=",", header=T)
Instead of the above, I want to define
refToMyTable <- "myTable"
Then, how can I use refToMyTable instead of myTable to read inputFile into myTable?
Thanks for the help.
R doesn't really have references like that, but you can use strings to retrieve/create variables of that name.
But first let me say this is generally not a good practice. If you're looking to do this type of thing, it's generally a sign that you're not doing it "the R way.'
Nevertheless
assign(refToMyTable, read.csv(inputFile, sep=",", header=T))
Should to the trick. And the complement to assign is get to retrieve a variable's value using it's name.
I think you mean something like the following:
reftomytable='~/Documents/myfile.csv'
myTable=read.csv(reftomytable)
Perhaps assign as mentioned by MrFlick.
When you want the contents of the object named "myTable" you would use get:
get("myTable")
get(refToMyTable) # since get will evaluate its argument
(It would be better to assign results of multiple such dataframes to a ist object or a Reference Class.)
If you wanted a language-name object you would use as.name:
as.name("myTable")
# myTable .... is printed at the console; note no quotes
str(as.name("myTable"))
#symbol myTable

Resources