【问题标题】:How to grep columns matching a pattern and calculate the row means of those columns and add the mean values as a new column to the data frame in r?如何grep与模式匹配的列并计算这些列的行均值并将平均值作为新列添加到r中的数据框?
【发布时间】:2019-10-28 16:24:04
【问题描述】:

我想 grep 列的名称并计算它们的行平均值并将平均值作为新列添加到数据框中。 这是我的数据框:

df <- data.frame(smp1.ex.rep1 = c(1,2,4,2), smp1.ex.rep2 = c(2,4,5,2), smp1.ex.rep3 = c(3,2,3,3), smp2.int.rep1 = c(3,2,4,5), smp2.int.rep2 = c(5,4,3,4), smp3.ex.rep1 = c(2,3,4,2), smp3.int.rep2 = c(1,3,5,6), smp3.int.rep3 = c(3,6,2,6))

我的 df 如下所示:

> df
 smp1.ex.rep1  smp1.ex.rep2  smp1.ex.rep3  smp2.int.rep1  smp2.int.rep2
    1             2              3               3               5
    2             4              2               2               4
    4             5              3               4               3
    2             2              3               5               4

我想 grep 具有相同模式的列直到“rep *”并计算它们的 rowmean 并将其变异为新列。

例如,将列 smp1.ex 与 rep1、rep2、rep3 放在一起,并将列 smp2.int 与最后的 rep1、rep2 放在一起。并将名称为 smp1、ex.mean 和 smp2.int.mean 的每组列的行均值添加到数据框中。

期望的输出是:

  smp1.ex.rep1 smp1.ex.rep2 smp1.ex.rep3 smp2.int.rep1 smp2.int.rep2 smp1.ex.mean smp2.int.mean
   1            2            3             3              5              2.00          4.0
   2            4            2             2              4              2.66          3.0
   4            5            3             4              3              4.00          3.5
   2            2            3             5              4              2.33          4.5

这是我想要做的:

names <- colnames(df)

names <- unique(gsub("rep*.*", "", names))
df <- rowMeans(df[,grep(paste(names[1:length(names)], 1:3, sep = "."), colnames(df))])

你有什么想法我该怎么做?

谢谢

【问题讨论】:

标签: r regex


【解决方案1】:

一个选项是使用sub 删除末尾的数字(\\d+$),将其用于split 数据集到data.frames 的list,获取rowMeans 并分配它到数据集中的新列

nm1 <- sub("\\d+$", "", names(df))
df[paste0(unique(nm1), "_mean")] <- sapply(split.default(df, nm1), rowMeans)

【讨论】:

    【解决方案2】:

    使用cbind 添加其他列,使用grepl(或grep)选择它们以传递给rowMeans

     df.new <- cbind( df, smp1.ex.mean = rowMeans( df[ , grepl("ex", names(df)] ),
                          smp2.int.mean = rowMeans( df[ , grepl("int", names(df)] )  )
    

    【讨论】:

      猜你喜欢
      • 2020-12-04
      • 2020-09-10
      • 2017-12-20
      • 1970-01-01
      • 2021-08-18
      • 2015-10-12
      • 2021-12-18
      • 1970-01-01
      • 2020-10-12
      相关资源
      最近更新 更多