Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete an element from a list of strings in R

Tags:

string

list

r

Among a few less relevant others, I checked these two answers:
Answer 1
Answer 2

However, the solutions presented there did not help.

I am probably misunderstanding my own problem and trying to do the right thing the wrong way. I appreciate any help.

I have the following code where I build a list of strings and try to delete the second element of the list:

> my_strings <- "string1 string2 string3 string4 string5"
> my_list <- strsplit(my_strings,split=" ")
> #Now trying to delete one element from my_list using positive indexing
>
> my_list[[2]] <- NULL #does not work
> my_list[2] <- NULL #nope. Doesn't work either
> my_list[[1]][2] <- NULL #error: replacement has length zero
> my_list[[1]][[2]] <- NULL # error: more elements supplied than there are to replace

So, my question is: how can I delete the second element (or multiple elements, like 1 and 3) of my_list? The elements of my_list are not named, I want to access them by the numeric index.

like image 429
bomgaroto Avatar asked Jul 16 '13 18:07

bomgaroto


1 Answers

I'm not sure you intended to create a list of vectors with your code; might be easier to just use a character vector. Try using unlist first:

my_list <- unlist(strsplit(my_strings,split=" "))

my_list <- my_list[-2]
like image 89
canary_in_the_data_mine Avatar answered Oct 17 '22 05:10

canary_in_the_data_mine