[英]How to include new rows and columns in a data frame (matrix) and perform a mathematical operation based on these in the dataset in R
[英]How do I perform mathematical operations between values in two columns of an R data frame based on their position?
我正在一個R項目中,嘗試比較頻率各自的值。 本質上,我在插槽1中具有一個11852X3列數據幀,其位置號在第二列中為唯一值,范圍從1-11852,然后在列3中的不同位置處具有相同的唯一值集。
本質上是因為第2列和第3列中的值重疊,所以我想根據最左側的位置編號(第1個)列查找這兩個值之間的差異,並將其存儲在另一個數據幀中。 因此,如果第二列在位置1處具有值2017,然后第三列在位置1處也具有2017,則新數據框將具有條目2017,然后具有值0,因為它們具有相同的位置。 如果列2在第二位置的值為5276,而列3在位置73的值為5276,則新數據幀的值將為70。
我希望獲得有關如何執行此操作的一些指導。 謝謝。
讓我知道下面的代碼是否對您有效。 如果第三列中的數字高於第二列中的數字,則代碼將生成負值。
#Generate simulated data
n = 20
x <- data.frame(c1 = c(1:n), c2 = sample(n),c3 = sample(n))
#Calculate diff in position by taking difference in order
x$diff = order(x$c3)- order(x$c2)
#Reassign difference to its correct position
x$diff[order(x$c2)] <- x$diff
x
c1 c2 c3 diff
1 1 12 8 4
2 2 11 5 9
3 3 7 4 6
4 4 15 3 12
5 5 19 12 12
6 6 13 1 12
7 7 9 14 12
8 8 18 16 7
9 9 8 7 -8
10 10 16 20 -2
11 11 6 11 1
12 12 4 6 -9
13 13 14 10 -6
14 14 5 17 -12
15 15 10 18 -2
16 16 1 15 -10
17 17 3 19 -13
18 18 2 13 2
19 19 17 9 -5
20 20 20 2 -10
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.