我有一个数据框test
,其列是因子
class(test)
[1] "data.frame"
sapply(test, class)
street city state
"factor" "factor" "factor"
如果我尝试将这些列转换为sapply()
的字符,则会出错并且我不确定原因
test <- as.data.frame(sapply(test, as.character))
sapply(test, class)
street city state
"factor" "factor" "factor"
我希望输出是所有字符列。为什么列不转换以及如何将所有因子列转换为字符?
以下是测试数据:
> dput(test)
structure(list(street = structure(c(5L, 1L, 6L, 2L, 3L, 4L), .Label = c("12057 Wilshire Blvd",
"15300 Sunset Boulevard", "17380 Sunset Blvd", "1898 Westwood Blvd.",
"3006 Sepulveda Blvd.", "514 Palisades Drive"), class = "factor"),
city = structure(c(1L, 1L, 2L, 2L, 2L, 3L), .Label = c("Los Angeles",
"Pacific Palisades", "Westwood"), class = "factor"), state = structure(c(1L,
1L, 1L, 1L, 1L, 1L), .Label = "CA", class = "factor")), .Names = c("street",
"city", "state"), row.names = c(NA, -6L), class = "data.frame")
答案 0 :(得分:2)
尝试mutate_if
,这也应该为您提供更多控制权:
mutate_if(test, is.factor, as.character)
答案 1 :(得分:1)
试试这个:
test[] <- lapply(test, as.character)
或者这个:
test <- modifyList(test, lapply(test, as.character))
或者这个:
test <- replace(test, TRUE, lapply(test, as.character))
答案 2 :(得分:0)
这应该可以解决问题,它会将apply
函数应用于数据帧的每一列。 as.data.frame
函数将返回一个矩阵,因此需要通过用test <- as.data.frame(apply(test, 2, as.character), stringsAsFactors = FALSE)
func convertType(from item: Int) -> Float {
return Float(item)
}
var item: Float = convertType(from: 1)