要创建一个空数据帧,将所需的行数和列数传入以下函数:
create_empty_table <- function(num_rows, num_cols) {
frame <- data.frame(matrix(NA, nrow = num_rows, ncol = num_cols))
return(frame)
}
要在指定每列的类的同时创建一个空帧,只需将所需数据类型的向量传递给下面的函数:
create_empty_table <- function(num_rows, num_cols, type_vec) {
frame <- data.frame(matrix(NA, nrow = num_rows, ncol = num_cols))
for(i in 1:ncol(frame)) {
print(type_vec[i])
if(type_vec[i] == 'numeric') {frame[,i] <- as.numeric(frame[,i])}
if(type_vec[i] == 'character') {frame[,i] <- as.character(frame[,i])}
if(type_vec[i] == 'logical') {frame[,i] <- as.logical(frame[,i])}
if(type_vec[i] == 'factor') {frame[,i] <- as.factor(frame[,i])}
}
return(frame)
}
使用方法如下:
df <- create_empty_table(3, 3, c('character','logical','numeric'))
这使:
X1 X2 X3
1 <NA> NA NA
2 <NA> NA NA
3 <NA> NA NA
要确认您的选择,运行以下命令:
lapply(df, class)
#output
$X1
[1] "character"
$X2
[1] "logical"
$X3
[1] "numeric"