Dataframe subsets retain information from parent dataframe - r

I assume this is used as a feature in data.frame() but it has presented a lot of problems for evaluating training and test sets for some packages. For example if you utilize h2o for machine learning, import a dataset, and subset the dataframe based on some random sample of the data, the h2o model builder will have access to the FULL original dataframe with all factor levels and all data. As such, if you try something like h2o.predict(model,newdata=dataset[test,]) your prediction will simply copy the response in the dataset over (tested for a deep learning model). You can see the factor retention below:
y = as.factor(c("1","0","0","1"))
X = c(5,4,3,4)
data = data.frame(y,X)
train = data[c(1,4),]
test = data[c(2,3),]
trainingData = data[train,]
trainingData
levels(trainingData[,1])
[1] "0" "1"
Now, I've been able to solve the factor information retention, but I'm not sure how to remove information from the parent dataframe in the new subset. Anyone have any ideas?
EDIT: For anyone who has had the factor problem, it's as simple as applying function droplevels().

Related

Cant understand what predict() does in this case

I am looking at some code that prepares a dataframe for several prediction models to be tested later on. The general idea is to predict NormSec based on all the other columns.
Not sure what predict(dummies,newdata=data) does in this case.
I know that predict is used to predict based on an already trained fit. Why is it used in this case? The code works, just trying to understand it.
data<-read.csv(file="datatable.csv")
attach(data)
#selecting the useful columns from data table:
data<-data.frame(NormSec, Rivalry,Stars,NormFB,SeasonPart,FootballSeason,LeBron,Weekend,LastSeasonWins
,Holiday,BigGame,OverUnders,DaysSinceLast,DaysUntilNext, Weekday, Monthday, NewArena)
dummies <- dummyVars(NormSec~., data = data)
attach(dummies)
#Here is the function I don't get:
dataDescr<-predict(dummies,newdata=data)
dataDescr<-data.frame(dataDescr)
attach(dataDescr)
dummies is a dummy variable object and DataDescr (output of predict()) is the original dataframe without the NormSec column.

Dummy coding omits / removes select variables from the data frame R

I have a fairly large dataset 1460(n)x81(p). About 38 variables are numeric and rest are factors with levels ranging from 2-30. I am using dummy.data.frame from *dummies package to encode the factor variables for use in running regression models.
However, as I run the following code:
train_dummy <- dummy.data.frame(train, sep = ".", verbose = TRUE, all = TRUE) some of the colums are from the original dataset are removed.
Has anyone encountered such issue before?
Link to original training dataset: https://www.kaggle.com/c/house-prices-advanced-regression-techniques/data
A number of columns from the original dataset including response variable SalePrice are being dropped. Any ideas/suggestions on what to try?
I wasn't able to reproduce the issue. I don't think there is enough info here to reproduce the issue, but I do have a few first thoughts.
run dummy data processing before train/test split
I see you're running the dummy data solely on your training data. I've found that it is usually a better strategy to run dummy data processing on the entire dataset as a whole, and then split into train / test.
Sometimes when you split first, you can run into issues with the levels of your factors.
Let's say I have a field called colors which is a factor in my data that contains the levels red, blue, green. If I split my data into train and test, I could run into a scenario where my training data only has red and blue values and no green. Now if my test dataset has all three, there will be a difference between the number of columns in my train vs test data.
I believe one way around that issue is the drop parameter in the dummy.data.frame function which defaults to TRUE.
things to check
Run these before running dummy data processing for train and test to see what characteristics these fields have that are being dropped:
# find the class of each column
train_class <- sapply(train, class)
test_class <- sapply(test, class)
# find the number of unique values within each column
unq_train_vals <- sapply(train, function(x) length(unique(x)))
unq_test_vals <- sapply(test, function(x) length(unique(x)))
# combine into data frame for easy comparison
mydf <- data.frame(
train_class = train_class,
test_class = test_class,
unq_train_vals = unq_train_vals,
unq_test_vals = unq_test_vals
)
I know this isn't really an "answer", but I don't have enough rep to comment yet.

Getting expected value through regression model and attach to original dataframe in R

My question is very similar to this one here , but I still can't solve my problem and thus would like to get little bit more help to make it clear. The original dataframe "ddf" looks like:
CONC <- c(0.15,0.52,0.45,0.29,0.42,0.36,0.22,0.12,0.27,0.14)
SPP <- c(rep('A',3),rep('B',3),rep('C',4))
LENGTH <- c(390,254,380,434,478,367,267,333,444,411)
ddf <- as.data.frame(cbind(CONC,SPECIES,LENGTH))
the regression model is constructed based on Species:
model <- dlply(ddf,.(SPP), lm, formula = CONC ~ LENGTH)
the regression model works fine and returns individual models for each species.
What I am going to get is the residual and expected value of 'Length' variable in terms of each models (corresponding to different species) and I want those data could be added into my original dataset ddf as new columns. so the new dataset should looks like:
SPP LENGTH CONC EXPECTED RESIDUAL
Firstly, I use the following code to get the expected value:
model_pre <- lapply(model,function(x)predict(x,data = ddf))
I loom there might be some mistakes in the above code, but it actually works! The result comes with two columns ( predicated value and species). My first question is whether I could believe this result of above code? (Does R fully understand what I am aiming to do, getting expected value of "length" in terms of different model?)
Then i used the following code to attach those data to ddf:
ddf_new <- cbind(ddf, model_pre)
This code works fine as well. But the problem comes here. It seems like R just attach the model_pre result directly to the original dataframe, since the result of model_pre is not sorted the same as the original ddf and thus is obviously wrong(justifying by the species column in original dataframe and model_pre).
I was using resid() and similar lapply, cbind code to get residual and attach it to original ddf. Same problem comes.
Therefore, how can I attach those result correctly in terms of length by species? (please let me know if you confuse what I am trying to explain here)
Any help would be greatly appreciated!
There are several problems with your code, you refer to columns SPP and Conc., but columns by those names don't exist in your data frame.
Your predicted values are made on the entire dataset, not just the subset corresponding to that model (this may be intended, but seems strange with the later usage).
When you cbind a data frame to a list of data frames, does it really cbind the individual data frames?
Now to more helpful suggestions.
Why use dlply at all here? You could just fit a model with interactions that effectively fits a different regression line to each species:
fit <- lm(CONC ~ SPECIES * LENGTH, data= ddf)
fitted(fit)
predict(fit)
ddf$Pred <- fitted(fit)
ddf$Resid <- ddf$CONC - ddf$Pred
Or if there is some other reason to really use dlply and the problem is combining 2 data frame that have different ordering then either use merge or reorder the data frames to match first (see functions like ordor, sort.list, and match).

Cannot coerce class ""amelia"" to a data.frame in R

I am using Amelia package in R to handle missing values.I get the below error when i am trying to train the random forest with the imputed data. I am not sure how can i convert amelia class to data frame which will be the right input to the randomForest function in R.
train_data<-read.csv("train.csv")
sum(is.na(train_data))
impute<- amelia(x=train_data,m=5,idvars=c("X13"), interacs=FALSE)
impute<= as.data.frame(impute)
for(i in 1:impute$m) {
model <- randomForest(Y ~X1+X2+X3+X4+X5+X6,
data= as.data.frame(impute))
}
Error in as.data.frame.default(impute) :
cannot coerce class ""amelia"" to a data.frame
If I used input to randomForest as impute$imputations[[i]] I the below error:
model <- randomForest(Y ~X1+X2+X3+X4+X5+X6,
impute$imputations[[i]])
Error: $ operator is invalid for atomic vectors
Can anyone suggest me how can I solve this problem .It would be a great help.
So, I think the first problem is this line here:
impute<= as.data.frame(impute)
Should be:
impute <- as.data.frame(impute)
Which will throw an error.
Multiple imputation replaces the data with multiple datasets, each with different replacements for the missing values. This reflects the uncertainty in those missing values predictions. By turning the Amelia object into a dataframe you are trying to make one data frame out of 5 data frames, and it's not obvious how to do this.
You might want to look into simpler forms of imputation (like imputing by the mean).
This is happening because you are trying to train on variable containing information on imputation you did. It does not have data you need to train on. You need to use the function complete to combine the imputed values in data set.
impute <- amelia(x=train_data,m=5,idvars=c("X13"), interacs=FALSE)
impute <- complete(impute,1)
impute <- as.data.frame(impute)
After this you won't have trouble training or predicting the data.

Nested data frame

I have got a technical problem which, as it seems, I am not able to solve by myself. I ran an estimation with the mcmcglmm package. By results$Sol I get access to the estimated posterior distributions. Applying class() tells me that the object is of class "mcmc". Using as.data.frame() results in a nested data frame which contains other data frames (one data frame which contains many other data frames). I would like to rbind() all data frames within the main data frame in order to produce one data frame (or rather a vector) with all values of all posterior distributions and the name of the (secondary) data frame as a rowname., Any ideas? I would be grateful for every hint!
Update: I didn't manage to produce a useful data set for the purpose of stackoverflow, with all these sampling chains these data sets would be always too large. If you want to help me, please consider to run the following (exemplaric) model
require(MCMCglmm)
data(PlodiaPO)
result <- MCMCglmm(PO ~ plate + FSfamily, data = PlodiaPO, nitt = 50, thin = 2, burn = 10, verbose = FALSE)
result$Sol (an mcmc object) is where all the chains are stored. I want to rbind all chains in order to have a vector with all values of all posterior distributions and the variable names as rownames (or since no duplicated rownames are allowed, as an additional character vector).
I can't (using the example code from MCMCglmm) construct an example where as.data.frame(model$Sol) gives me a dataframe of dataframes. So although there's probably a simple answer I can't check it very easily.
That said, here's an example that might help. Note that if your child dataframes don't have the same colnames then this won't work.
# create a nested data.frame example to work on
a.df <- data.frame(c1=runif(10),c2=runif(10))
b.df <- data.frame(c1=runif(10),c2=runif(10))
full.df <- data.frame(1:10)
full.df$a <- a.df
full.df$b <- b.df
full.df <- full.df[,c("a","b")]
# the solution
res <- do.call(rbind,full.df)
EDIT
Okay, using your new example,
require(MCMCglmm)
data(PlodiaPO)
result<- MCMCglmm(PO ~ plate + FSfamily, data=PlodiaPO,nitt=50,thin=2,burn=10,verbose=FALSE)
melt(do.call(rbind,(as.data.frame(result$Sol))))

Resources