0

this is probably a really stupid question, but I am big R newbie and. I have a matrix, which i need to frame. Is there a better way to do this, other than:

data1 = data.frame(X0 = Ytrain, X1 = Xtrain[,2], X2 = Xtrain[,3], ... , X50 = Xtrain[,51])

?

I was able to generate this monstrosity in Emacs, but now i need to create R function that does this. Any help would be greatly appriciated.

Tomas

2
  • Could you give a little more info about Ytrain and Xtrain? You write that you have a matrix, which I assume is Xtrain. Is Ytrain also a matrix? Or do both objects come from one original matrix? I ask because Ytrain might get recycled if it is shorter than nrow(Xtrain). Commented Jul 11, 2012 at 11:58
  • Yeah, i forgot to mention that. Ytrain is a column vector with same amount of rows as teh Xtrain. But guys below already figured that out. Commented Jul 11, 2012 at 11:59

2 Answers 2

3

This ought to do it:

# Assuming you used all the columns of `Xtrain` but the first
NEW.DF <- data.frame(Ytrain, Xtrain[, -1]) 
# If you didn't use all the cols of `xtrain`:
# NEW.DF <- data.frame(Ytrain, Xtrain[, 2:51])
names(NEW.DF) <- paste0("X", 0:(ncol(NEW.DF)-1))
Sign up to request clarification or add additional context in comments.

6 Comments

+1 (to help you get that silver R badge....). But according to the OP, Xtrain starts from the second column, so you should modify your answer accordingly.
Was taking care of that as you were typing :) Thanks
not sure if it was a typo, but i had to use paste("X", 0:(ncol(NEW.DF)-1),sep="") ... no biggie, though
@Arg, the function paste0 was added in R 2.15.0 and is equivalent to the way you used paste.
aha, that explains it. I use 2.14.1.
|
2
data1 <- cbind(data.frame(X0 = Ytrain),data.frame(Xtrain[, -1]))

Matrix columns are named X1...XN by default on conversion to data.frame unless they are already named.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.