我在這里有一個問題:
創建一個 10 行的虛擬資料幀“df_test”,包括列 (1)“INT1”,樣本值在 1 到 10 之間
- 創建一個接受兩個引數的函式“check_even”
(1) 'df' - 一個資料框
(2) 'col_test' - 列的名稱,用于測驗指示列中的每一行值是偶數還是奇數。
(3) 'col_multiply' - 如果 'col_test' 為偶數,則存盤 'col_test' 結果的列的名稱乘以 2,如果 'col_test' 為奇數,則乘以 3
(4) 函式以回傳整個 df 和結果結束
- 通過運行此代碼' check_even(df_test, 'INT1', 'res')' 測驗您的函式
這是我的代碼:
df_test = data.frame(INT1 = (sample(x = c(1:10),size = 10, replace = F)))
df_test
check_even = function(df, col_test, col_multiply) {
df$res = ifelse(df[col_test,] %% 2 == 0, df[,col_multiply] * 2, df[,col_multiply] * 3)
return(df)} #wrong
#run code
check_even(df_test, 'INT1','res')
在上面的代碼中,我得到:

我還嘗試了另一種使用 dplyr 的方法:
df_test = data.frame(INT1 = (sample(x = c(1:10),size = 10, replace = F)))
df_test
library(dplyr)
check_even = function(df, col_test, col_multiply){
df %>%
mutate(res = ifelse({{col_test}} %% 2 == 0, {{col_multiply}} * 2, {{col_multiply}} * 3))
}
check_even(df_test, 'INT1', 'res')
但是,我仍然收到錯誤訊息:
mutate(., res = ifelse({ : 由錯誤引起
"INT1" %% 2: ! 二元運算子的非數字引數
我該如何解決這個問題?先感謝您。
uj5u.com熱心網友回復:
堿基R
這是更正的基本 R 函式。
df_test = data.frame(INT1 = (sample(x = c(1:10),size = 10, replace = FALSE)))
#df_test
check_even = function(df, col_test, col_multiply) {
df[[col_multiply]] = ifelse(df[[col_test]] %% 2 == 0, df[[col_test]] * 2, df[[col_test]] * 3)
return(df)
}
#run code
check_even(df_test, 'INT1','res')
#> INT1 res
#> 1 4 8
#> 2 5 15
#> 3 1 3
#> 4 8 16
#> 5 2 4
#> 6 9 27
#> 7 3 9
#> 8 7 21
#> 9 10 20
#> 10 6 12
由reprex 包(v2.0.1)于 2022-06-04 創建
dplyr解決方案
library(dplyr)
check_even = function(df, col_test, col_multiply){
df %>%
mutate({{col_multiply}} := ifelse({{col_test}} %% 2 == 0, {{col_test}} * 2, {{col_test}} * 3))
}
check_even(df_test, INT1, res)
uj5u.com熱心網友回復:
我認為你需要這個,如果我沒有錯,你應該改變你的邏輯:
您可以在函式體中計算它,而不是將結果列作為引數傳遞:
library(dplyr)
check_even = function(df, col_test){
df %>%
mutate(res = ifelse({{col_test}} %% 2 == 0, {{col_test}} * 2, {{col_test}} * 3))
}
check_even(df_test, INT1)
INT1 res
1 10 20
2 3 9
3 6 12
4 4 8
5 7 21
6 9 27
7 5 15
8 2 4
9 1 3
10 8 16
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/487562.html
下一篇:R:從相鄰行中的條目創建隨機樣本
