【问题标题】:How to extract the results of R's strsplit() [duplicate]如何提取R的strsplit()的结果[重复]
【发布时间】:2018-09-19 07:59:37
【问题描述】:

关于:

我有一个字符串向量 foo:

>foo = c("1x2","3x4","5x6","7x8","9x10")

我将单个字符串拆分为“x”并将结果粘贴到 goo 中:

>goo = strsplit(foo, "x")
>goo
[[1]]
[1] "1" "2"

[[2]]
[1] "3" "4"

[[3]]
[1] "5" "6"

[[4]]
[1] "7" "8"

[[5]]
[1] "9"  "10"

如何从该列表中提取第一和第二“列”? (我想要(1,3,5,7,9)和(2,4,6,8,10))

【问题讨论】:

  • sapply(goo, identity) 然后对行进行切片。
  • read.table(text = foo, sep = 'x')[, 1]

标签: r strsplit


【解决方案1】:

使用sapply 使用“[[”进行串行“提取”:

 sapply(goo, "[[" , 1)
[1] "1" "3" "5" "7" "9"

我一直认为应该是这样的结果,但我可能不明白其中的问题。

【讨论】:

    【解决方案2】:
    > result <-  do.call(rbind, goo)
    > result
         [,1] [,2]
    [1,] "1"  "2" 
    [2,] "3"  "4" 
    [3,] "5"  "6" 
    [4,] "7"  "8" 
    [5,] "9"  "10"
    > result[, 1] # column 1
    [1] "1" "3" "5" "7" "9"
    > result[, 2] # column 2
    [1] "2"  "4"  "6"  "8"  "10"
    

    【讨论】:

      【解决方案3】:

      最简单的方法是将结果包装在 sapply 语句中

      odd_results <- sapply(goo, function(x) x[1])
      

      even_results <- sapply(goo, function(x) x[2])
      

      【讨论】:

        【解决方案4】:

        概述

        您需要指定按位置提取列表元素。

        # load data
        foo <- c("1x2","3x4","5x6","7x8","9x10")
        
        # split foo by 'x'
        foo.list <- strsplit( x = foo, split = "x", fixed = TRUE )
        
        # store the first and second elements of each list in a data frame
        foo.df <-
        data.frame(
            First_Element = unlist( lapply( X = foo.list, FUN = "[[", FUN.VALUE = 1 ) )
            , Second_Element = unlist( lapply( X = foo.list, FUN = "[[", FUN.VALUE = 2 ) )
          )
        

        【讨论】:

          【解决方案5】:

          为了多样化,你可以使用

          goo <- unlist(strsplit(foo, "x"))
          
          a <- goo[seq(1, length(goo), 2)]
          b <- goo[seq(2, length(goo), 2)]
          

          产量

          [1] "1" "3" "5" "7" "9"
          

          [1] "2"  "4"  "6"  "8"  "10"
          

          分别。

          【讨论】:

            猜你喜欢
            • 2014-02-17
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2018-11-27
            • 1970-01-01
            • 2020-05-14
            • 1970-01-01
            • 2020-12-16
            相关资源
            最近更新 更多