为什么 `apply` 函数无法检测 data.frame 的数字列并对其采取行动?
Why is the `apply` function not able to detect and act upon numeric columns of a data.frame?
当我尝试根据列的数据类型有条件地应用函数时,apply
出现了一个奇怪的行为。
这是函数。它检查 class()
然后执行合适的操作。
sampleF <- function(x){
DT = ifelse(class(x) == "numeric" | class(x) == "integer","Numbers",
ifelse(class(x) == "character" | class(x) == "factor","Text","Others"))
return(DT)
}
我正在尝试将其应用到下面 data.frame 并得到不正确的输出。
df1 <- data.frame(Col1 = letters[1:5],Col2 = 1:5,Col3 = as.factor(c("A","B","A","C","A")))
输出:
apply(df1,2,FUN = sampleF)
Col1 Col2 Col3
"Text" "Text" "Text"
另一方面,sapply
给出了正确的输出
sapply(df1,sampleF)
Col1 Col2 Col3
"Text" "Numbers" "Text"
apply
函数出现这种行为的原因可能是什么?
最好使用 lapply
在 data.frame
或某种程度上 sapply
中的列上应用函数。但是,对于 apply
,它将输出强制为 matrix
,并且它只能容纳一个 class。因此,如果有任何 character
元素,即使是数字列也会转换为 character
class.
out <- lapply(df1, sampleF)
unlist(out)
# Col1 Col2 Col3
# "Text" "Numbers" "Text"
另外,由于class
的length
为1,我们可以用if/else
或switch
代替ifelse
sampleF1 <- function(x){
cls <- class(x)
switch(cls,
numeric = "Numbers",
integer = "Numbers",
character = "Text",
factor = "Text",
"Others")
}
df2 <- cbind(df1, Col4 = TRUE)
lapply(df2, sampleF1)
#$Col1
#[1] "Text"
#$Col2
#[1] "Numbers"
#$Col3
#[1] "Text"
#$Col4
#[1] "Others"
当我尝试根据列的数据类型有条件地应用函数时,apply
出现了一个奇怪的行为。
这是函数。它检查 class()
然后执行合适的操作。
sampleF <- function(x){
DT = ifelse(class(x) == "numeric" | class(x) == "integer","Numbers",
ifelse(class(x) == "character" | class(x) == "factor","Text","Others"))
return(DT)
}
我正在尝试将其应用到下面 data.frame 并得到不正确的输出。
df1 <- data.frame(Col1 = letters[1:5],Col2 = 1:5,Col3 = as.factor(c("A","B","A","C","A")))
输出:
apply(df1,2,FUN = sampleF)
Col1 Col2 Col3
"Text" "Text" "Text"
另一方面,sapply
给出了正确的输出
sapply(df1,sampleF)
Col1 Col2 Col3
"Text" "Numbers" "Text"
apply
函数出现这种行为的原因可能是什么?
最好使用 lapply
在 data.frame
或某种程度上 sapply
中的列上应用函数。但是,对于 apply
,它将输出强制为 matrix
,并且它只能容纳一个 class。因此,如果有任何 character
元素,即使是数字列也会转换为 character
class.
out <- lapply(df1, sampleF)
unlist(out)
# Col1 Col2 Col3
# "Text" "Numbers" "Text"
另外,由于class
的length
为1,我们可以用if/else
或switch
代替ifelse
sampleF1 <- function(x){
cls <- class(x)
switch(cls,
numeric = "Numbers",
integer = "Numbers",
character = "Text",
factor = "Text",
"Others")
}
df2 <- cbind(df1, Col4 = TRUE)
lapply(df2, sampleF1)
#$Col1
#[1] "Text"
#$Col2
#[1] "Numbers"
#$Col3
#[1] "Text"
#$Col4
#[1] "Others"