2017-07-11 28 views
1

我想添加一個額外的列,顯示使用數據框中的2列的百分比更改。如何使用列的順序進行計算

例如,假設我的數據框有13列,每列有2行。並且行值都是數字。我想拿出第14列,結果來自使用第13和第12列的計算結果。

會這樣嗎?

df$additionalcolumn <- (df[,13] - df[,12])/df[,12] 
+2

你試過了嗎?結果是你的預期? –

+0

我發現另一個問題,嘗試下面的人回答的代碼。計算不起作用的原因是數據是「因子」格式。我不知何故需要將格式更改爲數字值。任何想法? –

+0

使用'as.character()'轉換爲字符串,然後使用'as.numeric()'轉換爲數字。不過,我建議改爲查看您的數據源以及如何將這些數據讀入R以確保它是正確的。你可能會發現'readr'包有幫助,因爲它的讀取功能更加冗長。 –

回答

1

我跑這個示例代碼,它工作正常。試試吧

test = data.frame(a=seq(1,10), b=seq(10,19)) 
test$c = test[,1] + test[,2] 
print(test) 

輸出

a b c 
1 1 10 11 
2 2 11 13 
3 3 12 15 
4 4 13 17 
5 5 14 19 
6 6 15 21 
7 7 16 23 
8 8 17 25 
9 9 18 27 
10 10 19 29 
+0

我發現嘗試上面的代碼的另一個問題。計算不起作用的原因是數據是「因子」格式。我不知何故需要將格式更改爲數字值。任何想法? –

+0

你可以'測試$ b = as.numeric(as.character(test $ b))''。這會將您的因子轉換爲數字。 – Nash

0

或通過data.table

library(data.table) # load the necessary packages 
test = data.table(a=seq(1,10), b=seq(10,19)) #create the data.table 
test[,c:=a+b]#create a new column named c and fill it with the sum of a and b