如何将行元素与列元素匹配并在 rstudio 中对它们执行计算
How to match elements of row with elements of a column and perform calculations on them in rstudio
我想将数据框列表中的列名 "Name" 匹配到数据框 "Volume" 的行名,并对列执行计算。
我可以使用匹配项或 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)
我想读取 List$Name 中的第一个元素与相应的列匹配,提取该列并对其执行简单的加法,并将结果存储在数据帧中 "Total"。我希望对行中的所有元素分别执行相同的操作。
List
S.No Name
2 Ba
1 Ar
5 Ca
3 Bl
4 Bu
Volume
Ar Ba Bl Bu Ca
-5.1275 1.3465 -1.544 -0.0877 3.2955
-2.2385 1.5065 0.193 1.082 3.074
-5.3705 1.1285 1.966 1.183 -1.9305
-6.4925 1.5735 1.36 -0.0761 2.0875
-5.068 0.9455 0.947 -0.7775 3.832
我知道这可以在合并两个文件并使用 sapply 函数后完成。但是因为我想在数据帧上使用 for 循环 "List" 我只想比较这两个数据帧并在每次循环结束后将结果分别存储到另一个数据帧。所以合并文件并不能帮助解决这个问题。
实际的List数据框由23条记录组成,实际的Volume数据框由18000条记录组成。
我正在尝试构建一个函数,但不确定此计算是否需要 for 循环。有没有更好更简单的方法来完成这个任务?
我不确定是否理解您的回答。
我认为您必须以这种方式更正您的代码:
for (i in 1: length(List$Name)) {
for (j in 1:dim(Volume)[2]) {
if(List$Name[i]==colnames(Volume[j])) Total[,i]<-Total[,i]+Volume[,j]
}
}
我已经使用代码
解决了将行元素与列元素匹配的问题
match(List$Name[i], names(Volume))
我想将数据框列表中的列名 "Name" 匹配到数据框 "Volume" 的行名,并对列执行计算。
我可以使用匹配项或 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)
我想读取 List$Name 中的第一个元素与相应的列匹配,提取该列并对其执行简单的加法,并将结果存储在数据帧中 "Total"。我希望对行中的所有元素分别执行相同的操作。
List
S.No Name
2 Ba
1 Ar
5 Ca
3 Bl
4 Bu
Volume
Ar Ba Bl Bu Ca
-5.1275 1.3465 -1.544 -0.0877 3.2955
-2.2385 1.5065 0.193 1.082 3.074
-5.3705 1.1285 1.966 1.183 -1.9305
-6.4925 1.5735 1.36 -0.0761 2.0875
-5.068 0.9455 0.947 -0.7775 3.832
我知道这可以在合并两个文件并使用 sapply 函数后完成。但是因为我想在数据帧上使用 for 循环 "List" 我只想比较这两个数据帧并在每次循环结束后将结果分别存储到另一个数据帧。所以合并文件并不能帮助解决这个问题。
实际的List数据框由23条记录组成,实际的Volume数据框由18000条记录组成。
我正在尝试构建一个函数,但不确定此计算是否需要 for 循环。有没有更好更简单的方法来完成这个任务?
我不确定是否理解您的回答。 我认为您必须以这种方式更正您的代码:
for (i in 1: length(List$Name)) {
for (j in 1:dim(Volume)[2]) {
if(List$Name[i]==colnames(Volume[j])) Total[,i]<-Total[,i]+Volume[,j]
}
}
我已经使用代码
解决了将行元素与列元素匹配的问题match(List$Name[i], names(Volume))