简体   繁体   中英

R Loop Script to Create Many, Many Variables

I want to create a lot of variables across several separate dataframes which I will then combine into one grand data frame.

Each sheet is labeled by a letter (there are 24) and each sheet contributes somewhere between 100-200 variables. I could write it as such:

a$varible1 <- NA
a$variable2 <- NA
.
.
.
w$variable25 <- NA

This can/will get ugly, and I'd like to write a loop or use a vector to do the work. I'm having a heck of a time doing it though.

I essentially need a script which will allow me to specify a form and then just tack numbers onto it.

So,

a$variable[i] <- NA

where [i] gets tacked onto the actual variable created.

I just learnt this neat little trick from @eddi

#created some random dataset with 3 columns
library(data.table)
        a <- data.table(
        a1 = c(1,5),
        a2 = c(2,1),
        a3 = c(3,4)
        )

#assuming that you now need to ad more columns from a4 to a200
# first, creating the sequence from 4 to 200
        v = c(4:200)
# then using that sequence to add the 197 more columns 
        a[, paste0("a", v) :=
                    NA]


# now a has 200 columns, as compared to the three we initiated it with
       dim(a)
       #[1]   2 200

I don't think you actually need this, although you seem to think so for some reason.

Maybe something like this:

a <- as.data.frame(matrix(NA, ncol=10, nrow=5))
names(a) <- paste0("Variable", 1:10)

print(a)
#   Variable1 Variable2 Variable3 Variable4 Variable5 Variable6 Variable7 Variable8 Variable9 Variable10
# 1        NA        NA        NA        NA        NA        NA        NA        NA        NA         NA
# 2        NA        NA        NA        NA        NA        NA        NA        NA        NA         NA
# 3        NA        NA        NA        NA        NA        NA        NA        NA        NA         NA
# 4        NA        NA        NA        NA        NA        NA        NA        NA        NA         NA
# 5        NA        NA        NA        NA        NA        NA        NA        NA        NA         NA

If you want variables with different types:

p <- 10 # number of variables
N <- 100 # number of records
vn <- vector(mode="list", length=p)
names(vn)  <- paste0("V", seq(p))
vn[1:8] <- NA_real_ # numeric
vn[9:10] <- NA_character_ # character
df <- as.data.frame(lapply(vn, function(x, n) rep(x, n), n=N))

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