Using strsplit ON a list in R [duplicate] - r

I'm just learning R and having a hard time wrapping my head around how to extract elements from objects in a list. I've parsed a json file into R giving me list object. But I can't figure out how, from there, to extract various json elements from the list. here's a truncated look at how my data appears after parsing the json:
> #Parse data into R objects#
> list.Json= fromJSON(,final.name, method = "C")
> head(listJson,6)
[[1]]
[[1]]$contributors
NULL
[[1]]$favorited
[1] FALSE
...[truncating]...
[[5]]
[[5]]$contributors
NULL
[[5]]$favorited
[1] FALSE
I can figure out how to extract the favorites data for one of the objects in the list
> first.object=listJson[1]
> ff=first.object[[1]]$favorited
> ff
[1] FALSE
But I'm very confused about how to extract favorited for all objects in the list. I've looked into sappily, is that the correct approach? Do I need to put the above code into a for...next loop?

sapply is going to apply some function to every element in your list. In your case, you want to access each element in a (nested) list. sapply is certainly capable of this. For instance, if you want to access the first child of every element in your list:
sapply(listJson, "[[", 1)
Or if you wanted to access the item named "favorited", you could use:
sapply(listJson, "[[", "favorited")
Note that the [ operator will take a subset of the list you're working with. So when you access myList[1], you still have a list, it's just of length 1. However, if you reference myList[[1]], you'll get the contents of the first space in your list (which may or may not be another list). Thus, you'll use the [[ operator in sapply, because you want to get down to the contents of the list.

Related

Referencing recently used objects in R

My question refers to redundant code and a problem that I've been having with a lot of my R-Code.
Consider the following:
list_names<-c("putnam","einstein","newton","kant","hume","locke","leibniz")
combined_df_putnam$fu_time<-combined_df_putnam$age*365.25
combined_df_einstein$fu_time<-combined_einstein$age*365.25
combined_df_newton$fu_time<-combined_newton$age*365.25
...
combined_leibniz$fu_time<-combined_leibniz$age*365.25
I am trying to slim-down my code to do something like this:
list_names<-c("putnam","einstein","newton","kant","hume","locke","leibniz")
paste0("combined_df_",list_names[0:7]) <- data.frame("age"=1)
paste0("combined_df_",list_names[0:7]) <- paste0("combined_df_",list_names[0:7])$age*365.25
When I try to do that, I get "target of assignment expands to non-language object".
Basically, I want to create a list that contains descriptors, use that list to create a list of dataframes/lists and use these shortcuts again to do calculations. Right now, I am copy-pasting these assignments and this has led to various mistakes because I failed to replace the "name" from the previous line in some cases.
Any ideas for a solution to my problem would be greatly appreciated!
The central problem is that you are trying to assign a value (or data.frame) to the result of a function.
In paste0("combined_df_",list_names[0:7]) <- data.frame("age"=1), the left-hand-side returns a character vector:
> paste0("combined_df_",list_names[0:7])
[1] "combined_df_putnam" "combined_df_einstein" "combined_df_newton"
[4] "combined_df_kant" "combined_df_hume" "combined_df_locke"
[7] "combined_df_leibniz"
R will not just interpret these strings as variables that should be created and be referenced to. For that, you should look at the function assign.
Similarily, in the code paste0("combined_df_",list_names[0:7])$age*365.25, the paste0 function does not refer to variables, but simply returns a character vector -- for which the $ operator is not accepted.
There are many ways to solve your problem, but I will recommend that you create a function that performs the necessary operations of each data frame. The function should then return the data frame. You can then re-use the function for all 7 philosophers/scientists.

Create a list with a number of objects from the local environment

ive created a lot of character objects in R that i would like to put into a list (storing all their information).
the object looks like this and the pattern is "TMC"
str(TMCS09g10086933)
chr [1:10] "TMCS09g1008699" "TMCS09g1008610 "TMCS09g10086101" "TMCS09g10086104" "TMCS09g100864343" "TMCS09g10086434343" "TMCS09g10086994111" ...
i have hundreds of these objects. Could someone tell me how to do this?
You can use the function objects with the argument pattern to list them.
Then, you can call the function get to fetch them. If you do this with an lapply, you will get a list returned right away.
TMClist <- lapply(objects(pattern = "^TMC"), get)
First you need to find the objects, which you can do with a regex search through the list of the objects in your environment grep("^TMC", ls(), value = TRUE), then you need to get the objects using the character vector of their names. For that you use mget.
your_list <- mget(grep("^TMC", ls(), value = TRUE))

R: Extract list element but without index number in output

This seems to be a beginner question but I couldn't find the answer anywhere. I know how to extract an element from a list using listname[[1]] but output will always include the index number like
[1] First element of the list
Same is true for using the name like listname$name or unlist(listname$name). All I want is
First element of the list
I could of course remove the index number using regex but I doubt that this is the way it should be :-)
The reason that the [1] appears is because all atomic types in R are vectors (of type character, numeric, etc), i.e. in your case a vector of length one.
If you want to see the output without the [1] the simples way is to cat the object:
> listname <- list("This is the first list element",
"This is the second list element")
> cat(listname[[1]], "\n")
This is the first list element
>

Delete position in key-value list in R

Note: I'm aware that there are tons of post about basic deletion on R, but the conventional method doesnt work for this case:
Using R, I've built a key-value pair list, in which both key and value are the same string. (Might seem strange but that's a different discussion ..)
name <- "foo"
list[[name]] <- name
Now I want to delete an element from the list again. Using the conventional method for deletion I tried:
list[[name]] <- NULL
However, this throws the following error:
Warning: Error in <-: more elements supplied than there are to replace
Does anyone know how to delete an element in a key-value list?
Cheers
Edit: Here are the relevant parts taken directly from my code
# saving the list element
networkName <- "Simulation_1_Run_1"
.GlobalEnv$netDynListName[[networkName]] <- (networkName)
# retrieval of the element
# ...
# deletion of list element which causes an error
.GlobalEnv$netDynListName[[networkName]] <- NULL

in R, extract part of object from list

I'm just learning R and having a hard time wrapping my head around how to extract elements from objects in a list. I've parsed a json file into R giving me list object. But I can't figure out how, from there, to extract various json elements from the list. here's a truncated look at how my data appears after parsing the json:
> #Parse data into R objects#
> list.Json= fromJSON(,final.name, method = "C")
> head(listJson,6)
[[1]]
[[1]]$contributors
NULL
[[1]]$favorited
[1] FALSE
...[truncating]...
[[5]]
[[5]]$contributors
NULL
[[5]]$favorited
[1] FALSE
I can figure out how to extract the favorites data for one of the objects in the list
> first.object=listJson[1]
> ff=first.object[[1]]$favorited
> ff
[1] FALSE
But I'm very confused about how to extract favorited for all objects in the list. I've looked into sappily, is that the correct approach? Do I need to put the above code into a for...next loop?
sapply is going to apply some function to every element in your list. In your case, you want to access each element in a (nested) list. sapply is certainly capable of this. For instance, if you want to access the first child of every element in your list:
sapply(listJson, "[[", 1)
Or if you wanted to access the item named "favorited", you could use:
sapply(listJson, "[[", "favorited")
Note that the [ operator will take a subset of the list you're working with. So when you access myList[1], you still have a list, it's just of length 1. However, if you reference myList[[1]], you'll get the contents of the first space in your list (which may or may not be another list). Thus, you'll use the [[ operator in sapply, because you want to get down to the contents of the list.

Resources