簡體   English   中英

使用依賴於數據幀的多列的 if 語句編寫 R 函數

[英]writing an R function with if statement that relies on multiple columns of a dataframe

我正在嘗試編寫一個包含 if 語句的 R 函數,其中當 A 列中的條件為真時,它會對 B 列中的值進行計算,否則它只返回 B 列中的值。我確定這很容易做到,我只是缺少一些基本的東西,但我很掙扎。 有沒有好的方法可以做到這一點?

這是我嘗試過的示例

example_df <- data.frame(
  type = c("oranges", "apples", "oranges", "oranges", "apples"),
  sold = c(6, 7, 1, 4, 1)
)

multiply_oranges <- function(x) { if (x$type == "oranges") {
    x$sold * 10
  } else {
    x$sold
  }
}
lapply(example_df, multiply_oranges)

但這給了我

Error: $ operator is invalid for atomic vectors

我無法理解這意味着什么/如何解決它。

在修復此功能或向我展示更好的方法方面的任何幫助將不勝感激。 謝謝!

  1. lapply不是必需的; 如果您有一個框架列表(甚至只有一個),那將很有用。 你沒有。 給您的函數的參數是一次一列。 它“展開”為:

     multiply_oranges(example_df$type) multiply_oranges(example_df$sold)

    這不是(我認為)你想要的。

  2. 你的if是錯誤的。 R 的if要求其條件長度為 1; 如果它更多,它會警告你:

     Warning in if (x$type == "oranges") { : the condition has length > 1 and only the first element will be used

    這有效地告訴您$type第一個值的值用於向量中的所有內容,這也(我相信)不是您想要的。 相反,請使用ifelse

嘗試這個:

multiply_oranges <- function(x) x$sold * ifelse(x$type == "oranges", 10, 1)
multiply_oranges(example_df)
# [1] 60  7 10 40  1

函數ifelse正在為向量中的每個元素執行條件。 如果你ifelseifelse ,你會看到

x$type == "oranges"
# [1]  TRUE FALSE  TRUE  TRUE FALSE
ifelse(x$type == "oranges", 10, 1)
# [1] 10  1 10 10  1
x$sold * ifelse(x$type == "oranges", 10, 1)
# [1] 60  7 10 40  1

我想知道這是否是你所追求的:

library(dplyr)
example_df %>% 
  mutate(Cost=ifelse(type=="oranges", sold*10, sold))
    type sold Cost
1 oranges    6   60
2  apples    7    7
3 oranges    1   10
4 oranges    4   40
5  apples    1    1

但這似乎需要很多努力,尤其是如果您想添加更多水果。 您應該有另一個包含每種水果價格的數據框。

Prices <- data.frame(price=c(10,5), type=c("oranges","apples"))
Prices
  price    type
1    10 oranges
2     5  apples

然后將它們連接起來並計算凈價:

library(tidyr)
example_df %>% 
  inner_join(Prices) %>%
  mutate(Net=sold*price)
Joining, by = "type"
     type sold price Net
1 oranges    6    10  60
2  apples    7     5  35
3 oranges    1    10  10
4 oranges    4    10  40
5  apples    1     5   5

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM