2017-07-29 78 views
1

我有一个数据帧DF:如何遍历R中包含变量的列名?

Shares Price1 Price2 Price3 
100  9   10  11 
200  5   6   7 
300  3   2   1 

我想循环移到该数据帧,并创建等于股份X价格三个新列[I],其中(i在1:3)。我尝试下面的代码:

for (j in 1:3) { 
    df$paste0("MktCap",j,sep="")<-df$Shares*df$paste0("Price",j,sep="") 
} 

但我得到的错误:

Error: attempt to apply non-function 

我看着here但它不太我想要的东西,因为我想我的新列名进行迭代。

+0

什么是您的预期输出 – Wen

回答

1

这是你想要的吗?此外,检查这里http://www.statmethods.net/management/subset.html

for (j in 1:3) { 
    df[,paste0("MktCap",j,sep="")]<-df$Shares*df[,paste0("Price",j,sep="")] 
} 


> df 
    Shares Price1 Price2 Price3 MktCap1 MktCap2 MktCap3 
1 100  9  10  11  900 1000 1100 
2 200  5  6  7 1000 1200 1400 
3 300  3  2  1  900  600  300 
1

链接@文的解决方案有效,如果你有很多价格栏,这将是一段路要走。但我认为使用dplyr你会得到一个更富于表现力的解决方案,更容易阅读和理解:

library(dplyr) 

df <- data.frame(Shares = c(100, 200, 300), Price1 = c(9, 5, 3), Price2 = c(10, 6, 2), Price3 = c(11, 7, 1)) 

(df <- df %>% 
    mutate(MktCap1 = Shares * Price1, 
     MktCap2 = Shares * Price2, 
     MktCap3 = Shares * Price3)) 

    Shares Price1 Price2 Price3 MktCap1 MktCap2 MktCap3 
1 100  9  10  11  900 1000 1100 
2 200  5  6  7 1000 1200 1400 
3 300  3  2  1  900  600  300 
1

考虑数据帧,DF:

df = tribble(
~Shares, ~Price1, ~Price2, ~Price3, 
100,  9,   10,   11, 
200,  5,   6,   7, 
300,  3,   2,   1 
) 

第一种方法 - 可怕。硬编码。这可行,但你想要一个可重复的解决方案。

df$Value1 = df$Shares * df$Price1 
df$Value2 = df$Shares * df$Price2 
df$Value3 = df$Shares * df$Price3 

第二条本办法 - 更好,但仍然不是很大。对于值集原单数据帧,按价格倍增,分配colnames,数据合并在一起

stockPrice = df[,2:4] 
stockValue = df$Shares * stockPrice 
colnames(stockValue) = c(paste("value", seq(1:3), sep = "")) 
cbind(df, stockValue) 

三(最好)的方法 - 定义一个函数!

calculateValues = function(df){ 
    N = ncol(df) 
    L = N-1 
    stockPrice = df[,2:N] 
    stockValue = df$Shares * stockPrice 
    colnames(stockValue) = c(paste("value", seq(1:L), sep = "")) 
    cbind(df, stockValue) 
} 

calculateValues(df) 

这应该输出一个新的数据帧,每次有份*值,命名和一切!唯一的问题是你的df的第一列每次都必须命名为“Shares”。