Matt
Matt

Reputation: 11

Loop over variables

I moved from Stata and have problem to match commands. Simply, I want to loop over variables in a data frame and manipulate/analyze, like the code below. Is there a way,for example defining a temporary variable (tmp) to carry the selected variable inside the loop and be addressed directly (like dt$tmp). I appreciate your comments.

The code below loops over columns to grab variable names and labels of a dataframe.

#Build the dataframe
dt <- data.frame(x=1:5,y=seq(1,10,2),z=seq(1,15,3))
attr(dt$x,'label') <- "First"
attr(dt$y,'label') <- "Second"
attr(dt$z,'label') <- "Third"


#loop over variables and store names and labels in a dataframe
names<- names(dt)
vars<- data.frame(id = 1:ncol(dt),var=NA,varlab =NA)
i <- 0
for(n in names){
  i <- i + 1
  nlab <- attr(dt[[paste(n)]], 'label')
  vars$var[i] <- n
  vars$varlab[i] <- nlab
}

To see this:

id var varlab

1 x First
2 y Second
3 z Third

Upvotes: 1

Views: 119

Answers (1)

BBlank
BBlank

Reputation: 76

It's hard to interpret what you are trying to accomplish. For example unless tmp is initially a column in df, this won't work, but it's hard for us to see your screen. If you need to define tmp as a new column you should cbind or dplyr::mutate in a new column.

If you just sketched out what you wanted it to look like that would be helpful too. You can make everything generic just help people help you.

Upvotes: 2

Related Questions