Creating separate objects from the index in a for loop

Viewed 26

I need a bit of help with a for loop please. Am relatively new to R.

For each element in v I want to generate separate named objects containing the data column names. I want to concatenate a letter ( eg. S) with the i elements in v. So I would make 'S id', 'S start', 'S end' as the named objects

v <- c("id", "start", "end")

for (i in v)
{
paste("S",i) <- colnames(df)[grepl(i, colnames(df))]
}

which gives a 'target of assignment expands to non-language object' error

I also tried something like:

D <- colnames(df)[grepl(i, colnames(df))]

assign(paste("S",i),D)

within the for loop but I can't seem to assign the values to different objects. I can't see any object named 'S id' for example being produced.

Basically for each element in v I want to make separate list objects (made up of the data columns matching the regular expression i).

1 Answers

The objects would be created in the global environment with assign

for(i in v) assign(paste("S", i), colnames(df)[grepl(i, colnames(df))])

-check for objects

> ls(pattern ="^S\\s+")
[1] "S end"   "S id"    "S start"

As there are space within the object element names, we need to use backquotes

> `S id`
[1] "id"

This may be also created with a multiple assignment operator (%=%)

library(collapse)
rm(list = ls(pattern ="^S\\s+"))
paste("S", v) %=%  colnames(df)[grepl(paste(v, collapse = "|"), colnames(df))]
`S id`
#[1] "id"

data

df <- data.frame(id = 1, start = 5, end = 10)
Related