简体   繁体   中英

Programmatically create arguments to data.frame in R

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

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))
data1 <- cbind(data.frame(X0 = Ytrain),data.frame(Xtrain[, -1]))

矩阵列在转换为data.frame默认情况下命名为X1 ... XN ,除非它们已经被命名。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM