我想將數據框List中的列名「Name」與數據框「卷」的Rowname匹配並對列執行計算。如何匹配行中的元素與列中的元素並在其中執行計算
我可以使用match或row.match來達到這個目的。
我試圖做這樣的事情
Total <- as.data.frame(matrix(0, ncol = 5, nrow = 5))
for (i in 1:5)
{
print(List$S.No[i] * 100)
for (j in 1:5)
{
if (match(List$Name, colnames(Volume)), 2]))
Value = Total + Volume[j]
print(Value)
}
}
print(Total)
問題的代碼:
Total <- as.data.frame(matrix(0, ncol = 5, nrow = 5))
for (i in 1:5)
{
print(List$S.No[i] * 100)
for (j in 1:5)
{
if (match(List$Name, colnames(Volume)), 2]))
# This match condition is not correct. I do not know how to call the column header
Value = Total + Volume[i]
# I want to add the data from the matching column to Total
print(Value)
}
}
print(Total)
我要與相應的列讀取列表$名稱匹配的第一個元素,提取列並對其執行簡單的添加並將結果存儲在數據幀「Total」中。我希望對該行中的所有元素分別進行同樣的操作。
List
S.No \t Name
2 \t Ba
1 \t Ar
5 \t Ca
3 \t Bl
4 \t Bu
Volume
Ar \t Ba \t Bl \t Bu \t Ca \t
-5.1275 \t 1.3465 \t -1.544 \t -0.0877 \t 3.2955 \t
-2.2385 \t 1.5065 \t 0.193 \t 1.082 \t 3.074 \t
-5.3705 \t 1.1285 \t 1.966 \t 1.183 \t -1.9305 \t
-6.4925 \t 1.5735 \t 1.36 \t -0.0761 \t 2.0875 \t
-5.068 \t 0.9455 \t 0.947 \t -0.7775 \t 3.832 \t
我知道這是可以合併兩個文件,並使用sapply功能後進行。但是因爲我想在數據幀「List」上使用for循環,所以我只想比較兩個數據幀,並在循環結束後每次將結果分別存儲到另一個數據幀。所以合併這些文件並不能解決這個問題。
實際列表數據框由23條記錄組成,實際卷數據框由18000條記錄組成。
我想建立一個函數,但不知道作爲for循環是必要的這種計算。有更好更簡單的方法來執行此任務嗎?
代碼有一些錯誤。錯誤if(List_Sample $ Name [i] == colnames(Volume [,j]))Total [,i] < - Total [,: 參數長度爲零。我不確定錯誤的含義。 – RVRLibra
對不起! if(List $ Name [i] == colnames(Volume [j]))。刪除姓名(卷[,j])中的',') –
即使這樣也行不通。錯誤'[.data.frame'(Total,,i):未定義的列被選中,這是錯誤。我認爲這是循環的問題。 – RVRLibra