【问题标题】:R: split string into numeric and return the mean as a new column in a data frameR:将字符串拆分为数字并将平均值作为数据框中的新列返回
【发布时间】:2015-06-16 02:08:57
【问题描述】:

我有一个大型数据框,其中的列是数字字符串,例如“1、2、3、4”。我希望添加一个新列,即这些数字的平均值。我已经设置了以下示例:

     set.seed(2015)
     library(dplyr)
     a<-c("1, 2, 3, 4", "2, 4, 6, 8", "3, 6, 9, 12")
     df<-data.frame(a)
     df$a <- as.character(df$a)

现在我可以使用 strsplit 来拆分字符串并返回给定行的平均值,其中 [[1]] 指定了第一行。

    mean(as.numeric(strsplit((df$a), split=", ")[[1]]))
    [1] 2.5

问题是当我尝试在数据框中执行此操作并引用行号时出现错误。

    > df2<- df %>%
    +   mutate(index = row_number(),
    +          avg = mean(as.numeric(strsplit((df$a), split=", ")
    [[index]])))
    Error in strsplit((df$a), split = ", ")[[1:3]] : 
      recursive indexing failed at level 2

谁能解释这个错误以及为什么我不能使用变量索引?如果我用一个常量替换 index 就可以了,它似乎不喜欢我在那里使用一个变量。

非常感谢!

【问题讨论】:

    标签: r recursion dplyr strsplit


    【解决方案1】:

    试试:

    library(dplyr)
    library(splitstackshape)
    
    df %>%
      mutate(index = row_number()) %>%
      cSplit("a", direction = "long") %>%
      group_by(index) %>%
      summarise(mean = mean(a))
    

    这给出了:

    #Source: local data table [3 x 2]
    #
    #  index mean
    #1     1  2.5
    #2     2  5.0
    #3     3  7.5
    

    或者按照@Ananda 的建议:

    > rowMeans(cSplit(df, "a"), na.rm = T)
    # [1] 2.5 5.0 7.5
    

    如果您想将结果保存在数据框中,您可以这样做:

    df %>% mutate(mean = rowMeans(cSplit(., "a"), na.rm = T))
    

    这给出了:

    #            a mean
    #1  1, 2, 3, 4  2.5
    #2  2, 4, 6, 8  5.0
    #3 3, 6, 9, 12  7.5
    

    【讨论】:

      【解决方案2】:

      您可以使用sapply 循环通过strsplit 返回的列表,处理每个列表元素:

      sapply(strsplit((df$a), split=", "), function(x) mean(as.numeric(x)))
      # [1] 2.5 5.0 7.5
      

      【讨论】:

        【解决方案3】:
        library(data.table)
        cols <- paste0("a",1:4)
        setDT(df)[, (cols) := tstrsplit(a, ",", fixed=TRUE, type.convert=TRUE)
                ][, .(Mean = rowMeans(.SD)), .SDcols = cols]
           Mean
        1:  2.5
        2:  5.0
        3:  7.5
        

        或者,

        rowMeans(setDT(tstrsplit(df$a, ",", fixed=TRUE, type.convert=TRUE)))
        # [1] 2.5 5.0 7.5
        

        【讨论】:

          猜你喜欢
          • 2020-08-07
          • 2011-05-20
          • 2014-11-18
          • 1970-01-01
          • 2020-11-20
          相关资源
          最近更新 更多