关于如何将data.frame的所有值从一种模式转换为另一种模式的问题已经足够多了。这就提出了以下问题:如何在 R 中转换 data.frame 的特定列?我有以下几点:
# @param dataFrame the data.frame to be transformed
# @param start the column which first needs to be rewritten to numeric data
# @param end the column which needs to be rewritten to numeric data as last
# @param exlude the columns that need to be excluded from rewriting to numeric data
asNumericData <- function (dataFrame,start,end,exclude) {
i <- start
asNumericMatrix <- matrix(nrow = length(dataFrame), ncol = ncol(dataFrame))
while (i <= end) {
if (!(i %in% exclude)) {
asNumericMatrix <- as.numeric(as.character(dataFrame[,i]))
}
i <- i + 1
}
return (asNumericMatrix)
}
但是,这会导致以下错误:
Error in asNumericMatrix[, i] <- as.numeric(as.character(dataFrame[, i])) : number of items to replace is not a multiple of replacement length
我做错了什么?关于如何将特定列(或更确切地说是排除列)从某种模式转换为另一种模式的任何其他建议也欢迎。
这是我过去的做法。给定一个列向量,迭代它们(通过 lapply),然后做你的 as.character、as.numeric、as.factor 等......
df <- data.frame(v=c("B","C","A"), w=c(12,14,17), h=c(1,2,3))
> str(df)
'data.frame': 3 obs. of 3 variables:
$ v: Factor w/ 3 levels "A","B","C": 2 3 1
$ w: num 12 14 17
$ h: num 1 2 3
cols <- c("w", "h")
df[,cols] <- lapply(df[,cols], as.character)
> str(df)
'data.frame': 3 obs. of 3 variables:
$ v: Factor w/ 3 levels "A","B","C": 2 3 1
$ w: chr "12" "14" "17"
$ h: chr "1" "2" "3"