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?
Yes, the [[
operator:
temp <- data.frame(x = 0:10, y = 10:20)
for (n in names(temp))
temp[[paste0(n, "_cumsum")]] <- cumsum(temp[[n]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With