【问题标题】:Calculate the number of occurrence of a given character in each row of a data frame?计算给定字符在数据帧的每一行中出现的次数?
【发布时间】:2016-05-17 17:04:24
【问题描述】:

我想计算以下字符的数量:

"AAA", "BBB", "CCC","DDD","EEE","FFF"

在这样的数据框中

 Id   Var1   Var2   Var3   Var4
  1   xtAAA  bBBB   fCCC   ::hFF
  2   xtAAA         ZEEE   ::FFF
  3   ooCCC  bBBB   CkCC   
  4          BBBh   fCCC   :-LLL
  5   xtAAA  lBBB   eCCC   ::FFF
  6                 BBBC   
  7   xtAAA  CvCC   fCCC   BBBlF

然后获取一个新的数据框:

 Id   Var1   Var2   Var3   Var4   number.of.AAA   number.of.BBB  number.of.CCC
  1   xtAAA  bBBB   fCCC   ::hFF
  2   xtAAA         ZEEE   ::FFF
  3   ooCCC  bBBB   CkCC   
  4          BBBh   fCCC   :-LLL
  5   xtAAA  lBBB   eCCC   ::FFF
  6                 BBBC   
  7   xtAAA  CvCC   fCCC   BBBlF

我看过很多脚本,但没有一个能达到我的目标。

【问题讨论】:

  • 请添加代码让我们重新创建数据框。另外添加预期输出是什么
  • 试试cbind(df1, t(apply(df1[-1], 1, function(x) sapply(v1, function(y) length(grep(y, x))))),其中v1是值的向量

标签: regex r dataframe


【解决方案1】:

以下应该做你想要的:

# smaller subset of the data
temp <- data.frame(matrix(c("xtAAA", "bBBB", "fCCC", "::hFF", "xtAAA","ZEEE", "::FFF"), byrow = T), stringsAsFactors=F)

# build a little counter function
counter <- function(strings, input) {
  return(sapply(strings, function(i) sum(grepl(i, input))))
}

# get the counts
myCounts <- t(sapply(1:nrow(temp), function(i) counter(strings=c("AAA", "BBB", "CCC"), temp[i,])))

您可以使用 cbind 将其添加到您的 data.frame:

allDone <- cbind(temp, myCounts)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    相关资源
    最近更新 更多