仅从具有混合值的单元格中提取数字

时间:2016-04-18 23:38:02

标签: r

我一直在寻找答案,找不到答案。我有一列数据,如:

22 apples, 16 oranges
13 plums, 22 large green grapes
52 fig leaves, 2 peanuts

我需要只提取每个单元格的数字,然后添加它们并将其放入新列中。非常感谢任何帮助!

3 个答案:

答案 0 :(得分:4)

您也可以通过使用字符矩阵进行提取,然后在此之后将其模式切换为数字而不循环遍历列。使用@ crippledlambda的数据m <- gsub("\\D+", "", as.matrix(table)) mode(m) <- "numeric" rowSums(m) # [1] 38 35 54 ,我们有

#ifndef id897
#define id897

struct FloatStash {
 struct node {
    float value;
    node* next;
 }* head;

 void init ( );
 void push ( float a );
 float pop ( );
 float* peek ( );
 void cleanup ( );
};

#endif

答案 1 :(得分:3)

x <- c("22 apples, 16 oranges",
       "13 plums, 22 large green grapes",
       "52 fig leaves, 2 peanuts")

虽然也可以使用基数R(例如gsub后跟strsplit)来完成,但stringr::str_extract_all很方便。

library(stringr)
numstr <- str_extract_all(x,"[0-9]+")

现在将字符串转换为数字并合并......

sapply(numstr,
       function(x) sum(as.numeric(x)))

答案 2 :(得分:1)

input <- "22 apples, 16 oranges
13 plums, 22 large green grapes
52 fig leaves, 2 peanuts"

table <- read.table(text=input, sep=",", col.names=c("first", "second"))

Strip <- function(x)
  gsub("^[ ]*|[ ]*$", "", x)

Getnumber <- function(x, pattern="^([0-9]+) (.+)$")
  as.numeric(sub(pattern, "\\1", Strip(x)))

table$sum <- Getnumber(table$first) + Getnumber(table$second)

然后你得到:

> table

          first                 second sum
1     22 apples             16 oranges  38
2      13 plums  22 large green grapes  35
3 52 fig leaves              2 peanuts  54

> table$sum
[1] 38 35 54