Home > Blockchain >  How can i remove specific element in a vector inside a list using index number in R programming
How can i remove specific element in a vector inside a list using index number in R programming

Time:09-22

I will try explaining it python where it would be helpful if some let me know how to do it in R programming

INPUT: I have a dict with list of values

my_dict = {
   data_point1:[
     {
       "sample1": "a"
     },
     {
       "sample2": "b"
     }
  ]
}

Now I want to remove sample1 obj inside data_points list, I can do this easily in python using pop provided with index number as 0

Expected_output:

my_dict = {
   data_point1:[
     {
       "sample2": "b"
     }
  ]
}

Please Note I have to remove elements inside list using index numbers only since its dynamically fetched n a forloop. It would be great if somebody helps me to implement this logic in R programming Thanks in advance!!!!

My Tries in R:

  • mydict[[data_point]][1] <- NULL
  • mydict[[data_point]] <- mydict[[data_point]][-1]

R data structure of input:

list(data_point = list("sample1" = c(1000,2), "sample2"= c(200,300)))

Here in need to remove the 1000 from sample1 element using index number

Expected output in R data structure:

list(data_point = list("sample1" = c(2), "sample2"= c(200,300)))

CodePudding user response:

If we need to assign the inner list element to NULL, extract the element with either $ or [[

mydict$datapoint$sample1 <- NULL

-output

> mydict
$data_point
$data_point$sample2
[1] "2"
> dput(mydict)
list(data_point = list(sample2 = "2"))

For the updated case, assign by taking the second element for the 'sample1'

mydict2$data_point$sample1 <- mydict2$data_point$sample1[2]
> dput(mydict2)
list(data_point = list(sample1 = 2, sample2 = c(200, 300)))

Or by index

mydict2$data_point$sample1 <- mydict2$data_point$sample1[-1]
> mydict2
$data_point
$data_point$sample1
[1] 2

$data_point$sample2
[1] 200 300

If we want to remove all 1st elements from the 'data_point', loop

mydict2$data_point <- lapply(mydict2$data_point, `[`, -1)
> mydict2
$data_point
$data_point$sample1
[1] 2

$data_point$sample2
[1] 300

Or using a for loop

 for(i in seq_along(mydict2$data_point)) 
      mydict2$data_point[[i]] <- mydict2$data_point[[i]][-1]
> mydict2
$data_point
$data_point$sample1
[1] 2

$data_point$sample2
[1] 300

CodePudding user response:

I would do something like this using purrr.

library(purrr)
my_list <- list(data_point = list("sample1" = c(1000,2), "sample2"= c(200,300)))

remove_value <- function(x, value) x[!x == value]
map_depth(my_list, 2, remove_value, value = 1000)
$data_point
$data_point$sample1
[1] 2

$data_point$sample2
[1] 200 300

Or to remove a specific index...

remove_index <- function(x, index) x[-index]
map_depth(my_list, 2, remove_index, index = 1)
  •  Tags:  
  • r
  • Related