add x variables to df , add df$x variables to x
df$x1 <- x1 x1 <- df$x1
df$x2 <- x2 x2 <- df$x2
... ...
df$x24 <- x24 x24 <- df$x24
formula_add <- c(paste(paste0("x", 1:24), collapse = " <- "))
formula_add
I have gotten this far.
[1] "x1 <- x2 <- x3 <- x4 <- x5 <- x6 <- x7 <- x8 <- x9 <- x10 <- x11 <- x12 <- x13 <- x14 <- x15 <- x16 <- x17 <- x18 <- x19 <- x20 <- x21 <- x22 <- x23 <- x24"
Can anyone help with this large # of variables data set? I don't know how to attach a small portion of it. Its ready. How to do? Thanks. MM
Flm
November 7, 2022, 4:31pm
2
Is this what you want?
v <- paste0("x", 1:24)
df <- paste0("df$x", 1:24)
final <- paste(df, v, sep = "<-")
final
[1] "df$x1<-x1" "df$x2<-x2" "df$x3<-x3" "df$x4<-x4" "df$x5<-x5" "df$x6<-x6" "df$x7<-x7" "df$x8<-x8"
[9] "df$x9<-x9" "df$x10<-x10" "df$x11<-x11" "df$x12<-x12" "df$x13<-x13" "df$x14<-x14" "df$x15<-x15" "df$x16<-x16"
[17] "df$x17<-x17" "df$x18<-x18" "df$x19<-x19" "df$x20<-x20" "df$x21<-x21" "df$x22<-x22" "df$x23<-x23" "df$x24<-x24"
Or maybe this?
n <- 1:24
df <- data.frame()
for(i in n) {
new <- rep(i, nrow(df))
df[ , ncol(df) + 1] <- new
colnames(df)[ncol(df)] <- paste0("x", i)
}
1 Like
mmarion
November 7, 2022, 11:24pm
3
Best results are
n <- 1:24
#df <- data.frame()
for(i in n) {
new <- rep(i, nrow(df))
df[ , ncol(df) + 1] <- new
colnames(df)[ncol(df)] <- paste0("x", i)
}
added columns are named correctly (x1-x24)
contents are not correct. contain integers 1-24
contents should be from titanic data set df
Note I write all variables to working memory first.
I then want to add 24 x variables to df using code provided.
id <- df$PassengerId
y <- df$Survived
x1 <- df$Pclass
x2 <- df$Sex
x3 <- df$Age
x4 <- df$SibSp
x5 <- df$Parch
x6t<- df$Ticket
x6 <- df$Fare
x7 <- df$Cabin
x8 <- df$Embarked
x9 <- Pclass2
x10 <- Pclass3
x11 <- Gender
x12 <- df$Age
x13 <- df$SibSp
x14 <- df$Parch
x15 <- df$Fare
x16 <- Cabin1
x17 <- Cabin2
x18 <- Cabin3
x19 <- Cabin4
x20 <- Cabin5
x21 <- Cabin6
x22 <- Cabin7
x23 <- Embarked1
x23 <- Embarked2
x24 <- Embarked3
system
Closed
December 19, 2022, 11:24pm
4
This topic was automatically closed 42 days after the last reply. New replies are no longer allowed. If you have a query related to it or one of the replies, start a new topic and refer back with a link.