2017-07-29 44 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」。