[英]ifelse didn't work in dataframe in R
我對R
ifelse
中的data.frame
有疑問。 我檢查了幾個SO帖子,不幸的是,這些解決方案都不適合我的情況。
我的情況是,在數據幀中進行條件計算,但返回the condition has length > 1 and only the first element will be used
即使在R
使用ifelse
函數后the condition has length > 1 and only the first element will be used
,根據我檢查的SO帖子,它應該可以完美地工作。
這是我的示例代碼:
library(scales)
head(temp[, 2:3])
previous current
1 0 10
2 50 57
3 92 177
4 84 153
5 30 68
6 162 341
temp$change = ifelse(temp$previous > 0, rate(temp$previous, temp$current), temp$current)
rate = function(yest, tod){
value = tod/yest
if(value>1){
return(paste("+", percent(value-1), sep = ""))
}
else{
return(paste("-", percent(1-value), sep = ""))
}
}
因此,如果我運行ifelse
,將得到以下結果:
head(temp[, 2:4])
previous current change
1 0 10 10
2 50 57 +NaN%
3 92 177 +NaN%
4 84 153 +NaN%
5 30 68 +NaN%
6 162 341 +NaN%
所以我的問題是,我應該如何處理? 在運行ifelse
之前,我嘗試將0
分配給最后一列,但仍然失敗。
提前謝謝了!
這是另一種方法
# 1: load dplyr
#if needed install.packages("dplyr")
library(dplyr)
# 2: I recreate your data
your_dataframe = as_tibble(cbind(c(0,50,92,84,30,162),
c(10,57,177,153,68,341))) %>%
rename(previous = V1, current = V2)
# 3: obtain the change using your conditions
your_dataframe %>%
mutate(change = ifelse(previous > 0,
ifelse(current/previous > 1,
paste0("+%", (current/previous-1)*100),
paste0("-%", (current/previous-1)*100)),
current))
結果:
# A tibble: 6 x 3
previous current change
<dbl> <dbl> <chr>
1 0 10 10
2 50 57 +%14
3 92 177 +%92.3913043478261
4 84 153 +%82.1428571428571
5 30 68 +%126.666666666667
6 162 341 +%110.493827160494
嘗試以下兩個部分,兩者都應該做您想要的。 可能這是您要查找的第二個。
library(scales)
set.seed(1)
temp <- data.frame(previous = rnorm(5), current = rnorm(5))
rate <- function(i) {
yest <- temp$previous[i]
tod <- temp$current[i]
if (yest <= 0)
return(tod)
value = tod/yest
if (value>1) {
return(paste("+", percent(value-1), sep = ""))
} else {
return(paste("-", percent(1-value), sep = ""))
}
}
temp$change <- unlist(lapply(1:dim(temp)[1], rate))
第二:
ind <- which(temp$previous > 0)
temp$change <- temp$current
temp$change[ind] <- unlist(lapply(ind,
function(i) rate(temp$previous[i], temp$current[i])))
在第二段中,功能rate
與您編寫的相同。
僅評估value
的第一個元素。 因此, rate
的輸出僅取決於temp
的第一行。
采納了我從熱情的SO用戶那里得到的建議,我對我的一些功能進行了矢量化,並且成功了! 向SO社區舉杯!
解決方法如下:
temp$rate = ifelse(temp$previous > 0, ifelse(temp$current/temp$previous > 1,
temp$current/temp$previous - 1,
1 - temp$current/temp$previous),
temp$current)
這將以科學計數法返回rate
。 如果需要“常規”符號,請進行以下更新:
temp$rate = format(temp$rate, scientific = F)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.