[英]Issues creating an if else statement for rounding with a loop in R
[英]Rounding in nested IF ELSE For loop
有沒有一種更干凈的方法來比較我的數據框的第三列,然后相應地將其除以1000、100或10? 我的代碼有效,但是有更好的方法編寫嗎?
划分之后,我想將其分配給“ Round to 1000”,以此類推。
df <- data.frame(y = c(1,2,3), y1 = c(2,3,4), y2 = c(1000, 100, 10))
df$Type <- 0
for (i in 1:nrow(df)){
if (df[i,3] %% 1000 == 0 ){
df[i,4] <- "Round to 1000"
} else if (df[i,3] %% 100 == 0){
df[i,4] <- "Round to 100"
} else if (df[i,3] %% 10 == 0){
df[i,4] <- "Round to 10"
} else {
df[i,4] <- "None"
}
}
根據我的經驗,大多數嵌套的if-else語句都可以由switch()
或dplyr::case_when()
:
library(dplyr)
df <- data.frame(
y = c(1, 2, 3, 5),
y1 = c(2, 3, 4, 5),
y2 = c(1000, 100, 10, 5)
)
df %>%
mutate(Type = case_when(
y2 %% 1000 == 0 ~ "Round to 1000",
y2 %% 100 == 0 ~ "Round to 100",
y2 %% 10 == 0 ~ "Round to 10",
TRUE ~ "NONE"
))
#> y y1 y2 Type
#> 1 1 2 1000 Round to 1000
#> 2 2 3 100 Round to 100
#> 3 3 4 10 Round to 10
#> 4 5 5 5 NONE
我認為case_when()
可以用一種清晰易讀的方式編寫...
在這種情況下,我通常去sapply
。 這很有幫助,因為它輸出可以插入到data.frame中的原子向量。
df$type <- sapply(df$y2, function(x) {
if (x %% 1000 == 0 ){
out <- "Round to 1000"
} else if (x %% 100 == 0){
out <- "Round to 100"
} else if (x %% 10 == 0){
out <- "Round to 10"
} else {
out <- "None"
}
out
})
輸出量
df
# y y1 y2 type
#1 1 2 1000 Round to 1000
#2 2 3 100 Round to 100
#3 3 4 10 Round to 10
在討論最佳方法時,可以選擇以下使用標准子集的方法。
df$type <- 'None'
for (i in c(10, 100, 1000)) {
df$type[df$y2 %% i == 0] <- paste('Round to', i)
}
要么:
df <- data.frame(y = c(1,2,3), y1 = c(2,3,4), y2 = c(1000, 100, 10))
txt <- c("Round to 1000", "Round to 100", "Round to 10", "None")
div <- c(1000, 100, 10, 1)
df$Type <- lapply(df$y2, function(x) {
txt[which.max(unlist(lapply(div, function(y) (x %% y) == 0)))]
})
#> df
#y y1 y2 Type
#1 1 2 1000 Round to 1000
#2 2 3 100 Round to 100
#3 3 4 10 Round to 10
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.