使用循环和命名约定在数据框中创建新的命名变量 [英] Creating new named variable in dataframe using loop and naming convention
本文介绍了使用循环和命名约定在数据框中创建新的命名变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
df $ var_cumul
temp< -as.data.frame(cbind(seq(0:10),seq(10:20)))
names(temp)< -c对于(i in 1:ncol(temp))的
{
vname< -names(temp)[i]
assign(paste(temp $ vname,_ cumul,sep =),cumsum(contrs [,i]))
}
没有找到我的工作。这可能是我R定期的最大的问题之一。
有没有一个简单直观的方法呢?
解决方案
是的, [[
operator:
temp < - data.frame(x = 0:10,y = 10:20)
for(n在名字(temp))
temp [[paste0(n,_cumsum)]]< - cumsum(temp [[n]])
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]])
这篇关于使用循环和命名约定在数据框中创建新的命名变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文