Home > Software design >  Treat elements in for loop as objects, not strings
Treat elements in for loop as objects, not strings

Time:12-08

I want to use a for-loop that treats the elements in a vector as objects.

df <- tibble(hallo1 = "test", hallo2.1 = "test", bye1 = "test", bye2.1 = "test")
segmente <- c("hallo", "bye")

for(i in segmente){
  assign(i, df[grepl(i, names(df))]) # first step
  assign(paste0(i, "_1"), i[!grepl("\\.", names(i))]) # second step
}

The first step in the for-loop works as intended and creates the objects hallo and bye as tibbles. The second step does not work as intended, because, i'm assuming, that in

i[!grepl("\\.", names(i))]

the i is treated as a string, and not as the created elements hallo and bye, resulting in empy strings, while they should be tibbles as well, only containing the columns without a ".".

How can i write it so the i is identified at what it is, a created object in the first step?

CodePudding user response:

In first step of loop i is "hallo" and has no names. If you want to call tibble with name "hallo" use get(i).

  • Related