climsaver
climsaver

Reputation: 617

Adding the same column to several data frames by looping

I have four data frames, each one consisting of 61 rows and 5 columns. They are called "London", "Chicago", "Frankfurt" and "Melbourne".

Now I want to replace the first column by the values from 1:61. This is what I tried and what did not work:

q <- 1:61

for (i in c("London", "Chicago", "Frankfurt", "Melbourne")) {
   get(i)[1] <- q
}

Does anybody have a solution which includes keeping the data frames and avoids working with lists?

Upvotes: 0

Views: 50

Answers (1)

Duck
Duck

Reputation: 39595

Try with a list:

#Value
q <- 61
#Objects
cities <- c("London", "Chicago", "Frankfurt", "Melbourne")
#List
List <- mget(ls()[grepl(paste0(cities,collapse = '|'),ls())])
#Loop
for (i in 1:length(List)) {
  List[[i]][,1] <- q
}

Upvotes: 1

Related Questions