使用ddply中的函数

时间:2013-09-13 18:46:56

标签: r if-statement plyr

我在将函数写入ddply调用时遇到问题。这是一个基本的DF:

library(plyr)

Time <- c(1,2,3,4,5,6,7,8,9,10)
X <- c(1,2,-3,4,-7,2,-4,9,7,-5)
Y <- c(2,-3,-4,4,4,3,2,-9,9,10)
T <- c(5,4,3,2,1,9,8,7,6,5)
DF <- data.frame(Time,X,Y,T)

我有两个不同的功能。希望从T中减去一个数字,取决于两列语句的结果

VD<-function(X,Y,T){
    if(X > 0 & Y < 0) {9-T}
    if(X < 0 & Y < 0) {5-T}
    if(X > 0 & Y > 0) {9-T}
    if(X < 0 & Y > 0) {5-T}
}

和第二个只看一个数字是负数还是正数(如果是负数则从9减去x,如果是正数则不做任何事情)

VD2<-function(X){
    if(X<0) {9-X}
    if(X>0) {X}
}

我写了我认为可行的内容

ddply(DF,'Time',summarize,Result=VD(X,Y,T))

ddply(DF,'Time',summarize,Result2=VD2(X))

但我两个都有错误,我不知道为什么

3 个答案:

答案 0 :(得分:2)

我认为你需要在函数中返回结果,即

VD<-function(X,Y,T){
if(X > 0 & Y < 0) {return(9-T)}
if(X < 0 & Y < 0) {return(5-T)}
if(X > 0 & Y > 0) {return(9-T)}
if(X < 0 & Y > 0) {return(5-T)}
}

答案 1 :(得分:2)

VD<-function(X,Y,T){
if(X > 0 & Y < 0) {k=9-T}
if(X < 0 & Y < 0) {k=5-T}
if(X > 0 & Y > 0) {k=9-T}
if(X < 0 & Y > 0) {k=5-T}
return(k)
}
library(plyr)
 ddply(DF,'Time',summarize,Result=VD(X,Y,T))
   Time Result
1     1      4
2     2      5
3     3      2
4     4      7
5     5      4
6     6      0
7     7     -3
8     8      2
9     9      3
10   10      0

VD2<-function(X){
    if(X<0) {k=9-X}
     if(X>0) {k=X}
     return(k)
 }
> ddply(DF,'Time',summarize,Result2=VD2(X))
   Time Result2
1     1       1
2     2       2
3     3      12
4     4       4
5     5      16
6     6       2
7     7      13
8     8       9
9     9       7
10   10      14

答案 2 :(得分:0)

另一种可行的方法,在&#34;一个&#34;功能:

  data2 <- plyr::ddply (DF, "Time", .fun=function(xx){
    c(Result=ifelse(xx[,"X"] > 0 & xx[,"Y"] < 0, {k=9-xx[,"T"]},
             ifelse(xx[,"X"] < 0 & xx[,"Y"] < 0, {k=5-xx[,"T"]}, 
             ifelse(xx[,"X"] > 0 & xx[,"Y"] > 0, {k=9-xx[,"T"]},
             ifelse(xx[,"X"] < 0 & xx[,"Y"] > 0, {k=5-xx[,"T"]}))))
    )})
#or

  data3 <- plyr::ddply (DF, "Time", .fun=function(xx){
    c(Result=     if(xx[,"X"] > 0 & xx[,"Y"] < 0) {k=9-xx[,"T"]}
             else if(xx[,"X"] < 0 & xx[,"Y"] < 0) {k=5-xx[,"T"]} 
             else if(xx[,"X"] > 0 & xx[,"Y"] > 0) {k=9-xx[,"T"]}
             else if(xx[,"X"] < 0 & xx[,"Y"] > 0) {k=5-xx[,"T"]}
  )})

# or 

data4 <- plyr::ddply (DF, "Time", .fun=function(df,t="T"){
  c(Result=ifelse(with(df, X > 0 & Y < 0), {k=9-df[,t]},
           ifelse(with(df, X < 0 & Y < 0), {k=5-df[,t]}, 
           ifelse(with(df, X > 0 & Y > 0), {k=9-df[,t]},
           ifelse(with(df, X < 0 & Y > 0), {k=5-df[,t]}))) )
  )})
data4
#or

data5 <- plyr::ddply (DF, "Time", .fun=function(df,t="T"){
  c(Result= if(with(df, X > 0 & Y < 0)) {k=9-df[,t]}
    else if(with(df, X < 0 & Y < 0)) {k=5-df[,t]} 
    else if(with(df, X > 0 & Y > 0)) {k=9-df[,t]}
    else if(with(df, X < 0 & Y > 0)) {k=5-df[,t]}
  )})
data5