Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating new named variable in dataframe using loop and naming convention

One of the most frustrating things about R is the difficulty of creating new dataframe variables using names, algorithmically and intuitively.

Suppose I have a dataframe with some variables, and want to create new variables based on them in a loop. For example, I want to create new variables which are the cumulative sum of existing variables, and named df$var_cumul

temp<-as.data.frame(cbind(seq(0:10),seq(10:20)))
names(temp)<-c("x","y")
for (i in 1:ncol(temp)) {
  vname<-names(temp)[i]
  assign(paste("temp$",vname,"_cumul",sep=""),cumsum(contrs[,i]))
}

No permuation of that I've found works. This is probably one of my biggest issue with R on a regular basis.

Is there an easy intuitive way to do this?

like image 701
Daniel Egan Avatar asked Jan 14 '13 18:01

Daniel Egan


1 Answers

Yes, the [[ operator:

temp <- data.frame(x = 0:10, y = 10:20)

for (n in names(temp))
  temp[[paste0(n, "_cumsum")]] <- cumsum(temp[[n]])
like image 197
Simon Urbanek Avatar answered Sep 29 '22 11:09

Simon Urbanek