简体   繁体   中英

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?

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

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)
}

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"
strsplit(list1$field2, ",")[[1]][2]

将访问第二个元素。

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

==> will access 2nd element

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

==> will access 5th element

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM