I am trying to use "rbind" to get the result but I am being shown an error "Error in rbind(deparse.level, ...) : invalid list argument: all variables should have the same length"
pm2 <- function(directory, id=1:322)
{
files <- list.files(path = directory, full.names = TRUE)
df <- data.frame()
for (i in 1:322)
{
fil <- read.csv(files[i])
df <- rbind(df, fil)
}
df2 <- data.frame(matrix(nrow = length(id), ncol = 2))
colnames(df2) <- c("id", "nobs")
for(i in id){
rbind(df2, c(df[[id[i]]],count((df[[id[i]]])),na.rm = TRUE))
}
df2
}
pm2("specdata", 1:10)
It sounds like your individual data frames do not have the same width (number of columns)
An easy fix is to use plyr::rbind.fill
which will fill in missing columns with NA
(although you might want to rethink why you're rbinding data frames of different widths). See the reproducible example below
test <- mtcars[1:2,]
ncol(test)
# [1] 11
modified <- test[,1:9]
ncol(modified)
# [1] 9
rbind(test, modified)
# Error in rbind(deparse.level, ...) :
# numbers of columns of arguments do not match
library(plyr)
rbind.fill(test, modified)
# mpg cyl disp hp drat wt qsec vs am gear carb
# 1 21 6 160 110 3.9 2.620 16.46 0 1 4 4
# 2 21 6 160 110 3.9 2.875 17.02 0 1 4 4
# 3 21 6 160 110 3.9 2.620 16.46 0 1 NA NA
# 4 21 6 160 110 3.9 2.875 17.02 0 1 NA NA