为什么我的函数遍历行而不是列?
我编写了以下函数,
compareColumns <- function(x) {
if (is.numeric(x)) {
paste("range", x, "=", range(x))
} else if (is.integer(x)) {
paste("table", x, "=", table(x))
} else if (is.logical(x)) {
paste("table", x, "=", table(x))
} else if (is.character(x) & length(unique(x)) <= 15) {
paste("table", x, "=", table (x))
} else {
paste("count unique", x, "=", length(unique(x)))
}
}
我希望输出是如果我对每一列手动执行所有这些操作(例如
apply(df, 2, length)
输出:
Column1 Column2 Column3 Column4
2115 2115 2115 2115
或
length(df$Column1)
< em>outputs
2115
相反,我得到
apply(df, 2, compareColumns)
outputs:
Column1
[1,] "count unique row1 = 212"
[2,] "count unique row2 = 212"
[3,] "count unique row3 = 212"
[4,] "count unique row4 = 212"
[5,] "count unique row5 = 212"
[6,] "count unique row6 = 212"
[7,] "count unique row7 = 212"
我哪里出错了?为什么我的函数不能仅应用于列?
I've written the following function
compareColumns <- function(x) {
if (is.numeric(x)) {
paste("range", x, "=", range(x))
} else if (is.integer(x)) {
paste("table", x, "=", table(x))
} else if (is.logical(x)) {
paste("table", x, "=", table(x))
} else if (is.character(x) & length(unique(x)) <= 15) {
paste("table", x, "=", table (x))
} else {
paste("count unique", x, "=", length(unique(x)))
}
}
I want the output to be the one I would get if I were doing all of those operations manually to each column such as
apply(df, 2, length)
outputs:
Column1 Column2 Column3 Column4
2115 2115 2115 2115
or
length(df$Column1)
outputs
2115
instead I get
apply(df, 2, compareColumns)
outputs:
Column1
[1,] "count unique row1 = 212"
[2,] "count unique row2 = 212"
[3,] "count unique row3 = 212"
[4,] "count unique row4 = 212"
[5,] "count unique row5 = 212"
[6,] "count unique row6 = 212"
[7,] "count unique row7 = 212"
Where am I going wrong? Why won't my function apply to columns only?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
lapply
而不是apply
,因为apply
转换为matrix
,因此只能有一个类型< /code> - 即,如果有一个列是
character
,它会将整个列转换为character
类,从而与apply
获得相同的输出> - 即它不能满足任何条件,从而进入else
条件另外,当我们使用
x
进行粘贴时,即列值、长度 将与行数相同
检查可重现的示例
Use
lapply
instead ofapply
asapply
converts tomatrix
and thus can have only a singletype
- i.e. if there is a single column that ischaracter
, it converts the whole intocharacter
class and thus got the same output withapply
- i.e. it couldn't satisfy any of the conditions and thus goes into theelse
conditionAlso, as we are
paste
ing withx
i.e. the column values, thelength
of the output will be the same as the number of rowsCheck with a reproducible example