2016-01-11 36 views
-5

我有以下数据(数据通过reshape2融化)。数据看起来像这样。数据的名称是k。如何整合定制功能?

variable  value 
Revenue  23.34 
Revenue  34.44 
Revenue   13 

我写这段代码从数据中抽取的第一位和最后一位数字:

require(plyr) 
require(stringr) 
k <- ddply(k, .(variable), transform, 
      first.digit = str_extract(value, "[123456789]"), 
      last.digit = str_extract(value, "[[:digit:]]$")) 

也许我需要尝试这种方法。确保要求所有的库。

k_function <- function(data){ 
require(plyr) 
require(stringr) 
ddply(data, .(variable), transform, 
     first.digit = str_extract(value, "[123456789]"), 
     last.digit = str_extract(value, "[[:digit:]]$")) -> k_data 
return(k_data) 
} 

应用数据看起来像这样的代码之后:

variable  value first.digit last.digit 
Revenue  23.34  2    4 
Revenue  34.44  3    4 
Revenue  13  1    3 

我怎样才能纳入量身定制的整个过程做出功能。

回答

2

这将工作(你可以了解如何编写函数,例如这里:http://www.r-bloggers.com/how-to-write-and-debug-an-r-function/):

my_function <- function(data){ 

    ddply(data, .(variable), transform, 
      first.digit = str_extract(value, "[123456789]"), 
      last.digit = str_extract(value, "[[:digit:]]$")) -> new_data 
    return(new_data) 
} 

my_function(k) 
+0

非常感谢。我不明白这部分代码的作用是什么 - > new_data和return(new_data)。你能详细解释一下吗? –

+0

你不明白哪部分代码? – ytk

+0

通过'ddply()'我创建一个新的数据帧,我保存为一个局部变量'new_data'。函数有这个属性,它在我们的情况下需要一些值(在我们的例子中是'data')并且返回一个值('new_data')。现在清楚吗? – Marta