[英]R applying function on a dataframe
I am trying to apply this function: 我正在尝试应用此功能:
if.class <- function(data){
as.data.frame(
if (data == '[1, 4)') '1'
else if (data == '[4, 6)') '2'
else '3'
)
}
on a entire data frame in order to transform the factor levels [1, 4) and [4, 6) to 1 or 2 or 3. The dataframe looks like this: 为了将因子级别[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)
I am using this line for the transformation: 我正在使用以下行进行转换:
mnm.predict.test.class.factors <- apply(mnm.predict.test.class,c(1,2),if.class)
However, the results is weird: 但是,结果很奇怪:
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
any ideas why the transformation is not working as expected ? 有什么想法为什么转换没有按预期进行?
You can use the levels
function to alter the levels of a factor
. 您可以使用levels
功能更改factor
的级别。 For example, if you have the factor variable foo
例如,如果您有因子变量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)
you can change the levels like this 你可以这样改变水平
levels(foo) <- c("1","2","3","3")
R> foo
[1] 1 2 3 3 1 2 3 3
Levels: 1 2 3
In your case, you have a 1 column data.frame
, so it would be something like 在您的情况下,您有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
And just as a side note, judging by the output of head(mnm.predict.test.class.factors)
in your question, it looks like your one column has the unwieldy name predict(mnm, newdata = testing.logist, type = "class")
- you might want to change this to something more reasonable to type ( names(mnm.predict.test.class.factors)[1] <- "myVar"
for example). 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
returns an array
and thus your output. apply
返回一个array
,因此输出。 Convert it to a data.frame
and you ll be fine: 将其转换为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.