nukubiho
nukubiho

Reputation: 338

Operations on data frames in the loop

I have three data frame and I would like to perform some operation on them in the loop (transpose and assign names to columns). The problem with my code is that the data frames are not updated and the result is a completely new data frame.

df1 = data.frame(A = c(1, 2), B = c(1, 2))
df2 = data.frame(A = c(1, 2), B = c(1, 2))
df3 = data.frame(A = c(1, 2), B = c(1, 2))

names = c("df1", "df2", "df3")

for(df in names) {
  df = get(names)
  df = t(df)
  colnames(df) = df[1, ]
  df = df[-1, ]
}

Upvotes: 0

Views: 57

Answers (1)

Dave2e
Dave2e

Reputation: 24079

My recommendation is place all of the dataframes in a list and then work with the list instead of the individual dataframes.

df1 = data.frame(A = c(1, 2), B = c(1, 2))
df2 = data.frame(A = c(1, 2), B = c(1, 2))
df3 = data.frame(A = c(1, 2), B = c(1, 2))

names = list(df1, df2, df3)

names<-lapply(names, function(df){
  df = t(df)
  colnames(df) = df[1, ]
  df = df[-1, ]
})

Of course the list "names" have then updated dataframes and the original dataframes are untouched.

EDIT In order to address your comment of reducing data redundancy. I tweaked your code and used the assign() function to update the data frames in the global environment.

df1 = data.frame(A = c(1, 2), B = c(1, 2))
df2 = data.frame(A = c(1, 2), B = c(1, 2))
df3 = data.frame(A = c(1, 2), B = c(1, 2))

names = c("df1", "df2", "df3")

for(name in names) {
  df = get(name)
  df = t(df)
  colnames(df) = df[1, ]
  df = df[-1, ]
  assign(name, df)
}

Upvotes: 2

Related Questions