0

我在将函数写入 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))

但我都得到了错误,我不知道为什么

4

3 回答 3

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
于 2013-09-13T19:32:02.177 回答
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)}
}
于 2013-09-13T19:19:50.040 回答
0

在“一个”功能中也可以使用的另一种可能性:

  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
于 2017-09-08T20:37:03.297 回答