ShanZhengYang
ShanZhengYang

Reputation: 17631

How to use strsplit() to access elements in an R list?

I have an R list list1, whereby one field was made to be two strings concatenated with together.

When we acces the field field3 for list1, it looks like this

list1$field2

 [1] "stringA, stringB"    
 [2] "stringA, stringB"      
 [3] "stringA, stringB" 
 [4] "stringA, stringB" 
 [5] "stringA, stringB" 
 [6] "stringA, stringB"             
 ....

I would only like to access the entries "stringB", and ignore "stringA".

If I use something like strsplit(), I get the following:

strsplit(list1$field2, ",")
[[1]]
[1] "stringA"
[2] "stringB"
[[2]]
[1] "stringA"
[2] "stringB"
....

This is a list where each member has two elements. How do I only access the second element? Is there a way to make this more syntactically compact?

Upvotes: 2

Views: 2949

Answers (5)

Agus BudiCandra
Agus BudiCandra

Reputation: 21

strsplit(list1$field2, ",")[[1]][[2]]

==> will access 2nd element

strsplit(list1$field2, ",")[[1]][[5]]

==> will access 5th element

Upvotes: 2

B P Kailash
B P Kailash

Reputation: 1

strsplit(list1$field2, ",")[[1]][2]

will access the second element.

Upvotes: 0

Simon Jackson
Simon Jackson

Reputation: 3174

A "tidyverse" approach similar to suggestion in comments by @GavinSimpson:

library(purrr)
library(stringr)

x <- rep("stringA, stringB", 10)

str_split(x, ", ") %>% map_chr(`[`, 2)
#>  [1] "stringB" "stringB" "stringB" "stringB" "stringB" "stringB" "stringB"
#>  [8] "stringB" "stringB" "stringB"
  • str_split() acts like strsplit().
  • map_chr() acts like lapply(), but also converts resulting list to a character vector.

For your problem, substitute x for list1$field2

Upvotes: 4

IRTFM
IRTFM

Reputation: 263332

This will read that vector and parse as a text file, so then you can just take the second "column"

 scan(text=list1$field2, what=list("",""))[[2]]
Read 6 records
[1] "stringB" "stringB" "stringB" "stringB" "stringB" "stringB"

Upvotes: 1

Dave2e
Dave2e

Reputation: 24079

Here is function which is fast for converting a 2 element string to a data frame:

strToDf<-function (list){
  slist<-strsplit(list, ",")
  x<-sapply(slist, FUN= function(x) {x[1]})
  y<-sapply(slist, FUN= function(x) {x[2]})
  #x<-as.numeric(x)
  #y<-as.numeric(y)
  df<-data.frame(x=x, y=y, stringsAsFactors = FALSE)
  return(df)
}

Upvotes: 1

Related Questions