簡體   English   中英

我的函數中的循環不會改變我的數據類型(在 R 中)

[英]The Loop in My Function does not change my data type (in R)

我打算使用一個函數來節省重復程序的打字工作。 許多事情已經在起作用,但並非一切都在起作用。 這是代碼:

quicky <- function(df, factors){
      output <- as.character(substitute(factors)[-1])
      print(output)
      df[,output]
      for(i in names(df[,output])){
        hist(df[,as.character(i)])
        df[,as.character(i)] <- as.factor(df[,as.character(i)])#<- Why does this not work?
      }
    }

quicky(mtcars, c(cyl,hp,drat))

請求幫助和解釋! 提前致謝。

當我們遍歷從 'output' 創建的列名時,只需遍歷這些列名,而不是進一步對數據進行子集化並獲取 te names 另外,在函數中,最后return數據集

quicky <- function(df, factors){
      output <- as.character(substitute(factors)[-1])
      print(output)
     for(i in output){               
          df[[i]] <- as.factor(df[[i]])
           }

           df

    }

out <- quicky(mtcars, c(cyl,hp,drat))
str(out)
#'data.frame':  32 obs. of  11 variables:
# $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
# $ cyl : Factor w/ 3 levels "4","6","8": 2 2 1 2 3 2 3 1 1 2 ...  ###
# $ disp: num  160 160 108 258 360 ...
# $ hp  : Factor w/ 22 levels "52","62","65",..: 11 11 6 11 15 9 20 2 7 13 ...###
# $ drat: Factor w/ 22 levels "2.76","2.93",..: 16 16 15 5 6 1 7 11 17 17 ...###
# $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
# $ qsec: num  16.5 17 18.6 19.4 17 ...
# $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
# $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
# $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
# $ carb: num  4 4 1 1 2 1 4 2 2 4 ...

注意:將[更改為[[以便它適用於data.tabletbl_df

quickly的原因是未能將分配結果返回到df的列是 R for循環的一個特殊功能。 它返回NULL。 在您的quicky函數中評估的最后一個函數是for 因此,您需要做的就是在循環外添加對df值的調用:

quicky <- function(df, factors){
    output <- as.character(substitute(factors)[-1])
    print(output)
    df[,output]
    for(i in names(df[,output])){
        hist(df[,as.character(i)])
        df[, i] <- as.factor(df[, i ])
    }; df  # add a call to evaluate `df` 
}

str( quicky(mtcars, c(cyl,hp,drat)) )
#-------
[1] "cyl"  "hp"   "drat"
'data.frame':   32 obs. of  11 variables:
 $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
 $ cyl : Factor w/ 3 levels "4","6","8": 2 2 1 2 3 2 3 1 1 2 ...
 $ disp: num  160 160 108 258 360 ...
 $ hp  : Factor w/ 22 levels "52","62","65",..: 11 11 6 11 15 9 20 2 7 13 ...
 $ drat: Factor w/ 22 levels "2.76","2.93",..: 16 16 15 5 6 1 7 11 17 17 ...
 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 $ qsec: num  16.5 17 18.6 19.4 17 ...
 $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
 $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
 $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
 $ carb: num  4 4 1 1 2 1 4 2 2 4 ..

這種行為for形成對比,在R.大多數其他功能有了一個for循環,評價和內完成它的任務通常生效外for -loop體,即在調用環境,但該函數調用自身返回NULL . 大多數其他函數在它們的函數體環境之外沒有任何效果,如果需要任何持久效果,則需要程序員將返回值分配給命名對象。 (當然,您不應該期望mtcars的價值會受到該操作的影響。)

暫無
暫無

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

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