[英]R assign variable types to large data.frame from vector
我有一個寬的data.frame
,它是所有字符向量( df1
)。 我有一個單獨的vector
( vec1
),其中包含要分配給df1
每個列的列類。
如果使用的是read.csv()
,我將使用colClasses
參數並將其設置為vec1
,但對於現有的data.frame
似乎沒有類似的選擇。
除了循環之外,還有什么建議可以快速實現此目的?
我不知道這是否會有幫助,但是我多次遇到相同的需求,並且創建了一個函數以防萬一:
reclass <- function(df, vec){
df[] <- Map(function(x, f){
#switch below shows the accepted values in the vector
#you can modify it and/or add more
f <- switch(f,
as.is = 'force',
factor = 'as.factor',
num = 'as.numeric',
char = 'as.character')
#takes the name of the function and fetches the function
f <- get(f)
#apply the function
f(x)
},
df,
vec)
df
}
它使用Map
將類的向量傳遞給data.frame
。 每個元素對應於該列的類。 數據幀和向量的長度必須相同。
我也在使用switch
來使相應的類更短一些。 使用as.is
來保持類的相同,其余的我都可以自我解釋。
小例子:
df1 <- data.frame(1:10, letters[1:10], runif(50))
> str(df1)
'data.frame': 50 obs. of 3 variables:
$ X1.10 : int 1 2 3 4 5 6 7 8 9 10 ...
$ letters.1.10.: Factor w/ 10 levels "a","b","c","d",..: 1 2 3 4 5 6 7 8 9 10 ...
$ runif.50. : num 0.0969 0.1957 0.8283 0.1768 0.9821 ...
和之后的功能:
df1 <- reclass(df1, c('num','as.is','char'))
> str(df1)
'data.frame': 50 obs. of 3 variables:
$ X1.10 : num [1:50] 1 2 3 4 5 6 7 8 9 10 ...
$ letters.1.10.: Factor w/ 10 levels "a","b","c","d",..: 1 2 3 4 5 6 7 8 9 10 ...
$ runif.50. : chr [1:50] "0.0968757788650692" "0.19566105119884" "0.828283685725182" "0.176784737734124" ...
我猜Map在內部是一個循環,但它是用C
編寫的,因此應該足夠快。
可能您可以嘗試執行相同功能的此功能。
reclass <- function (df, vec_types) {
for (i in 1:ncol(df)) {
type <- vec_types[i]
class(df[ , i]) <- type
}
return(df)
}
這是vec_types(類型的向量)的示例:
vec_types <- c('character', rep('integer', 3), rep('character', 2))
您可以通過此表(df)測試函數(重分類):
table <- data.frame(matrix(sample(1:10,30, replace = T), nrow = 5, ncol = 6))
str(table) # original column types
# apply the function
table <- reclass(table, vec_types)
str(table) # new column types
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.