简体   繁体   English

将R中具有不同行长的文件读入列表

[英]Read in R a file with different line lengths into a List

I would like to read a file into a list of arrays with each line representing a list element. 我想将文件读入数组列表,每行代表一个列表元素。 Each line has a different number of elements and different The first value in the line would be the list key and the remaining data would be the members of the array. 每行具有不同数量的元素,并且不同。该行中的第一个值将是列表键,而其余数据将是数组的成员。

eg file example 例如文件示例

1 100,50,2,5,78
2 5,4,2,1
3 1
4 7,2,9,0,23,5,6,7,8,2,3,4
5 1,2,3,4,5,6,7,8,9,0
6 1,8

I think this should work well 我认为这应该很好

dd<-scan("example.txt", list("character", "character"))
Map(function(a,b)b, dd[[1]], strsplit(dd[[2]],","))

Here use use scan to read the first column as one vector and the second as another. 在这里,使用use scan将第一列作为一个向量,将第二列作为另一个向量。 Then we strsplit the second on commas and use one of the side-effects of Map to pull the names from the first column and use them as labels of the vectors from the second column. 然后,我们将第二个拆分为逗号,并使用Map的副作用之一从第一列中提取名称,并将其用作第二列中向量的标签。 If you wanted the vector values to be numeric you could do 如果您希望向量值为数字,则可以执行

Map(function(a,b) as.numeric(b), dd[[1]], strsplit(dd[[2]],","))

# $`1`
# [1] 100  50   2   5  78
# 
# $`2`
# [1] 5 4 2 1
# 
# $`3`
# [1] 1
# 
# $`4`
#  [1]  7  2  9  0 23  5  6  7  8  2  3  4
# 
# $`5`
#  [1] 1 2 3 4 5 6 7 8 9 0
# 
# $`6`
# [1] 1 8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM