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?
$<-do something it cannot do. It would also help if you unlearned the abomination ofas.data.frame(cbind(...))1:ncol,1:nrowor1:length... (it doesn't do what you think it does and such cases are a pain to debug ...) - you want to useseq_len()and friends instead.data.frame(x = 1:11, y = 1:11)is (among other things) a whole lot less typing. I would seriously recommend playing around with the output of things likeseq(10:20)because that's pretty horrible too. (Reading?seqwould be a good start.)cbindcoerces to a matrix, which removes all attributes and makes all columns the "lowest possible denominator" generally a character matrix.