PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, November 1, 2022

[FIXED] How can I remove an element from a list by index, when the index matches a value from another list?

 November 01, 2022     indexing, list, r, r-faq     No comments   

Issue

I have a list (list_a) with values and I want to remove all values from that list that have a certain index. To do this I already have a separate list (list_b) that has all the indexes that I want to remove as its values. Now I want to remove from list_a all the values that have an index that matches a value from list_b.

To make it easy to understand here is an example:

list_a <- list("One", "Two", "Three", "Four", "Five") # original list

list_b <- list(2, 4) # indexes that I want to remove from list_a

# Desired Output:
# [1] "One" "Three" "Five" 

I tried doing the following:

list_c <- list_a[-c(list_b)]
# But got the following error:
# Error : invalid argument to unary operator

Because I know that I can remove the indexes in the following manner:

list_c <- list_a[-c(2,4)]

But I don't want to know the values that I want to remove beforehand, can't I use a list as an argument to remove indexes of another list?


Solution

You can’t index using a list; you need to use an atomic vector. You can solve your issue by

  1. Creating list_b as a numeric vector to begin with:
list_b <- c(2, 4)
list_a[list_b]
  1. Or converting to an atomic vector using as.numeric() or unlist().
# either
list_a[as.numeric(list_b)]
# or
list_a[unlist(list_b)]


Answered By - zephryl
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing