我有一个看起来像这样的大数据框:
> my_table
track_fid start_gid end_gid
1 1 100 82
2 2 82 100
3 3 100 82
4 4 100 32
5 5 82 100
6 6 82 100
7 7 82 100
8 8 100 82
9 9 34 100
10 10 31 100
我的目标是添加列
to_from
最后并用字符填充它 y
或 n
.我们以第一行为例——
start_gid
中的值= 100 和 end_gid
中的值= 82. 如果表中存在相反值的任何其他行,即,其中 end_gid
= 100 和 start_gid
中的值= 82,我想填列to_from
两行 y
.如果逆不存在,第一行应该用 n 填充。这里的关键是遍历每一行并按照track_fid
的顺序在表中查找它的逆序。 .如果在 track_fid
处找到逆更大,应该插入一个 y。一旦逆接收到一个值 y
,不能再次使用。例如,这将是一个示例输出:
> output
track_fid start_gid end_gid to_from
1 1 100 82 y
2 2 82 100 y
3 3 100 82 y
4 4 100 32 n
5 5 82 100 y
6 6 82 100 y
7 7 82 100 n
8 8 100 82 y
9 9 34 100 n
10 10 31 100 n
有没有办法在 R 中创建这样的输出?
类似的东西:
for(i in 2:nrow(my_table)) {
if(my_table[i-1,"start_gid"]= my_table[i,"end_gid"]) {
my_table$to_from = "y" } else { my_table$to_from = "n"}
> str(output)
'data.frame': 10 obs. of 4 variables:
$ track_fid: int 1 2 3 4 5 6 7 8 9 10
$ start_gid: int 100 82 100 100 82 82 82 100 34 31
$ end_gid : int 82 100 82 32 100 100 100 82 100 100
$ to_from : Factor w/ 2 levels "n","y": 2 2 2 1 2 2 1 2 1 1
最佳答案
我在 R 中没有看到没有循环的方法。你可以用 for
来做到这一点。循环和 next
和 break
声明。但在这种情况下,如果问题很大,我会求助于 Rcpp。
library(Rcpp)
sourceCpp(code = "
#include <Rcpp.h>
// [[Rcpp::export]]
Rcpp::LogicalVector myfun(const Rcpp::IntegerVector x, const Rcpp::IntegerVector y) {
Rcpp::LogicalVector res(x.length());
for (int i=0; i<(x.length()-1); i++) {
if(res(i)) continue;
for (int j=i+1; j<x.length(); j++) {
if (res(j)) continue;
if (x(i) == y(j) && x(j) == y(i)) {
res(i) = true;
res(j) = true;
break;
}
}
}
return res;
}
")
DF$from_to <- myfun(DF$start_gid, DF$end_gid)
# track_fid start_gid end_gid from_to
#1 1 100 82 TRUE
#2 2 82 100 TRUE
#3 3 100 82 TRUE
#4 4 100 32 FALSE
#5 5 82 100 TRUE
#6 6 82 100 TRUE
#7 7 82 100 FALSE
#8 8 100 82 TRUE
#9 9 34 100 FALSE
#10 10 31 100 FALSE
关于r - R 中的对称对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41391503/