我需要在列上执行一个函数来填充另一列,该列表示行中的数字是增长还是(保持或减少)。我正在考虑4个值:
df<-data.frame(a=c('cli1','cli2','cli3'),b=c(3,8,6), c=c(2,6,7), d=5:7, e=c(1,5,10), f=1:3)
该功能将是:
f2<-function (tbl) {x<-data.frame(cid=tbl[,1])
for (i in 5:(ncol(tbl)) ) {
if
((tbl[,i]+tbl[,i-1])/(tbl[,i-2]+tbl[,i-3])-1 >0)
{Y='sube'}
else if
((tbl[,i]+tbl[,i-1])/(tbl[,i-2]+tbl[,i-3])-1<=0)
{Y='baja'}
x[,paste('_Disc',colnames(tbl)[i],sep='')]<-Y
}
return (x)}
当我申请时,我得到:
Warning messages: 1: In if ((tbl[, i] + tbl[, i - 1])/(tbl[, i - 2] + tbl[, i - 3]) > : the condition has length > 1 and only the first element will be used
如何逐行使用if来逐行使用?感谢。
答案 0 :(得分:1)
尝试:
f2New <- function(tbl) {
x <- data.frame(cid = tbl[, 1])
for (i in 5:(ncol(tbl))) {
indx <- (tbl[, i] + tbl[, i - 1])/(tbl[, i - 2] + tbl[, i - 3])
Y <- ifelse(indx > 0, "sube", ifelse(indx2 <= 0, "baja", NA))
x[, paste("_Disc", colnames(tbl)[i], sep = "")] <- Y
}
return(x)
}
f2New(df)
# cid _Disce _Discf
#1 cli1 <NA> sube
#2 cli2 sube sube
#3 cli3 sube sube