使用循环和命名约定在数据框中创建新的命名变量 [英] Creating new named variable in dataframe using loop and naming convention

查看:377
本文介绍了使用循环和命名约定在数据框中创建新的命名变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于R的最令人沮丧的事情之一是使用名称,算法和直观地创建新的数据帧变量的难度。假设我有一个包含一些变量的数据框,并希望根据循环创建新的变量。例如,我想创建新变量,这是现有变量的累积和,并命名为 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆