繁体   English   中英

R:将字符串拆分为数字,并将均值作为数据框中的新列返回

[英]R: split string into numeric and return the mean as a new column in a data frame

我有一个大型数据框,其中的列是一个数字字符串,如“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

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

非常感谢!

尝试:

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

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

sapply(strsplit((df$a), split=", "), function(x) mean(as.numeric(x)))
# [1] 2.5 5.0 7.5
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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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