簡體   English   中英

R在數據框上應用功能

[英]R applying function on a dataframe

我正在嘗試應用此功能:

if.class <- function(data){
  as.data.frame(
  if (data == '[1, 4)')   '1'
  else if (data == '[4, 6)')  '2'
  else '3'
)
}

為了將因子級別[1,4)和[4,6)轉換為1或2或3,在整個數據幀上。該數據幀如下所示:

> dim(mnm.predict.test.class)
  [1] 5750    1
  > head(mnm.predict.test.class)
   predict(mnm, newdata = testing.logist, type = "class")
  1                                                 [1, 4)
  2                                                 [1, 4)
  3                                                 [1, 4)
  4                                                 [1, 4)
  5                                                 [1, 4)
  6                                                 [1, 4)

我正在使用以下行進行轉換:

 mnm.predict.test.class.factors <- apply(mnm.predict.test.class,c(1,2),if.class)

但是,結果很奇怪:

 head(mnm.predict.test.class.factors)
 predict(mnm, newdata = testing.logist, type = "class")
 [1,] List,1                                                
 [2,] List,1                                                
 [3,] List,1                                                
 [4,] List,1                                                
 [5,] List,1                                                
 [6,] List,1   

有什么想法為什么轉換沒有按預期進行?

您可以使用levels功能更改factor的級別。 例如,如果您有因子變量foo

foo <- factor(
  rep(c("[1, 4)","[4, 6)","[6, 7)","[7, 9)"),2))
R> foo
[1] [1, 4) [4, 6) [6, 7) [7, 9) [1, 4) [4, 6) [6, 7) [7, 9)
Levels: [1, 4) [4, 6) [6, 7) [7, 9)

你可以這樣改變水平

levels(foo) <- c("1","2","3","3")
R> foo
[1] 1 2 3 3 1 2 3 3
Levels: 1 2 3

在您的情況下,您有1列data.frame ,所以它就像

Df <- data.frame(
  foo = factor(
    rep(c("[1, 4)","[4, 6)",
          "[6, 7)","[7, 9)"),2)))
##
levels(Df[,1]) <- c("1","2","3","3")
R> str(Df)
'data.frame':   8 obs. of  1 variable:
 $ foo: Factor w/ 3 levels "1","2","3": 1 2 3 3 1 2 3 3

head(mnm.predict.test.class.factors) ,根據您問題的head(mnm.predict.test.class.factors)的輸出判斷,您的一列看起來像是個predict(mnm, newdata = testing.logist, type = "class")名字predict(mnm, newdata = testing.logist, type = "class") -您可能希望將其更改為更合理的類型(例如names(mnm.predict.test.class.factors)[1] <- "myVar" )。

apply返回一個array ,因此輸出。 將其轉換為data.frame ,就可以了:

#example data
df <- data.frame(a=rep('[1, 4)',50) )

> df
        a
1  [1, 4)
2  [1, 4)
3  [1, 4)
4  [1, 4)
5  [1, 4)
6  [1, 4)
7  [1, 4)
8  [1, 4)
9  [1, 4)

#just use your function as you used it but wrapped inside a data.frame function
df2 <-  data.frame(apply(df,c(1,2),if.class))

> df2
   a
1  1
2  1
3  1
4  1
5  1
6  1
7  1
8  1
9  1

暫無
暫無

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

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