创建具有多个列的Edgelist,n/as在R中

发布于 2025-01-23 09:14:12 字数 590 浏览 2 评论 0原文

正在研究R。

看起来有点像这样:

      V1 V2 V3 V4
   1   1  2  3  NA
   2   2  3  NA NA
   3   2  4  1  NA
   4   1 NA  NA NA

但是更大。我很难从这些数据中创建Edgelist并尝试过:

myPairs <- apply(t(df), 2, function(x) t(combn(x[!is.na(x)], 2)))

但是继续遇到此错误:

h(simpleerror(msg,call))中的错误:评估参数的错误 'x'在选择功能't'的方法时:n&lt; m

输出应该看起来像这样:

      col1   col2
   1  1      2
   2  1      3
   3  2      3
   4  2      3
   5  2      4
   6  2      1
   7  1      4

任何帮助都将不胜感激!

I am working on igraph in R.

I have a dataframe (df) with 29 columns - some rows which all have values and some which have NAs.

It looks a little something like this:

      V1 V2 V3 V4
   1   1  2  3  NA
   2   2  3  NA NA
   3   2  4  1  NA
   4   1 NA  NA NA

but much larger. I am having trouble creating an edgelist from this data and have tried:

myPairs <- apply(t(df), 2, function(x) t(combn(x[!is.na(x)], 2)))

but keep getting this error:

Error in h(simpleError(msg, call)) : error in evaluating the argument
'x' in selecting a method for function 't': n < m

The output should look like this:

      col1   col2
   1  1      2
   2  1      3
   3  2      3
   4  2      3
   5  2      4
   6  2      1
   7  1      4

Any help would be very much appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅笑轻吟梦一曲 2025-01-30 09:14:12

这是一种方法。

确保您的data.frame是数字:

df <- sapply(df, as.numeric)

您可以在完成上使用应用 combn,但首先使用na.omit 缺少值。您还可以检查length,因此,如果您一排仅具有一个值,则会跳过它。

do.call(rbind, apply(df, 1, function(x) {
  y <- na.omit(x)
  if (length(y) > 1)
    t(combn(y, 2))
}))

输出

     [,1] [,2]
[1,]    1    2
[2,]    1    3
[3,]    2    3
[4,]    2    3
[5,]    2    4
[6,]    2    1
[7,]    4    1

Here is one approach.

Making sure your data.frame is numeric:

df <- sapply(df, as.numeric)

You can use apply with combn as you've done, but first use na.omit to remove missing values. You can also check the length so that if you only have one value in a row you skip it.

do.call(rbind, apply(df, 1, function(x) {
  y <- na.omit(x)
  if (length(y) > 1)
    t(combn(y, 2))
}))

Output

     [,1] [,2]
[1,]    1    2
[2,]    1    3
[3,]    2    3
[4,]    2    3
[5,]    2    4
[6,]    2    1
[7,]    4    1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文