gpt4 book ai didi

r - 在R中将非矩形数据导入为矩形

转载 作者:行者123 更新时间:2023-12-02 06:55:56 25 4
gpt4 key购买 nike

我需要加载社交网络数据,其中每个用户都有未知且可能有大量 friend ,存储为以下格式的文本文件:

UserId: FriendId1, FriendId2, ...
1: 12, 33
2:
3: 4, 6, 10, 15, 16

变成一个两列的data.frame:

  UserId FriendId
1 1 12
2 1 33
3 3 4
4 3 6
5 3 10
6 3 15
7 3 16

你会如何在 R 中做到这一点?

读取、填充和整形效率低下,因为它需要在内存中保留许多充满 NA 的列。

相关问题here , 和 here .

最佳答案

如果你真的有一个冒号作为分隔符,那么只需使用 read.tableheader = FALSE 将你的数据放入 R,然后考虑使用 cSplit 来 self 的“splitstackshape”包。

mydf <- read.table("test.txt", sep = ":", header = FALSE)
mydf
## V1 V2
## 1 1 12, 33
## 2 2
## 3 3 4, 6, 10, 15, 16

library(splitstackshape)
cSplit(mydf, "V2", ",", "long")
## V1 V2
## 1: 1 12
## 2: 1 33
## 3: 3 4
## 4: 3 6
## 5: 3 10
## 6: 3 15
## 7: 3 16

关于r - 在R中将非矩形数据导入为矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31352802/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com