繁体   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