Reputation: 363
I have a below stdin input and I am trying to convert this input to a list.
Input
input <- suppressWarnings(readLines(stdin(), n=31))
8 30
a s 3
b s 5
s a 3
b a 1
c a 10
d a 11
s b 5
a b 3
c b 2
d b 3
a c 10
b c 2
d c 3
e c 7
f c 12
a d 15
b d 7
c d 2
e d 11
f d 2
c e 7
d e 11
f e 3
z e 2
c f 12
d f 2
e f 3
z f 2
e z 2
f z 2
Line 1 first value denotes total number of alphabets , Second value denotes total number of rows. From Line 2 to Line n. First value denotes starting node , second is ending node and third is cost.
I want to group the alphabets and cost as a list in below manner.
Expected output
> alphabets
$s
[1] "a" "b"
$a
[1] "s" "b" "c" "d"
$b
[1] "s" "a" "c" "d"
$c
[1] "a" "b" "d" "e" "f"
$d
[1] "a" "b" "c" "e" "f"
$e
[1] "c" "d" "f" "z"
$f
[1] "c" "d" "e" "z"
$z
[1] "e" "f"
> cost
$s
[1] 3 5
$a
[1] 3 1 10 11
$b
[1] 5 3 2 3
$c
[1] 10 2 3 7 12
$d
[1] 15 7 2 11 2
$e
[1] 7 11 3 2
$f
[1] 12 2 3 2
$z
[1] 2 2
Any suggestions from where to start.?
Upvotes: 1
Views: 110
Reputation:
Does this give you what you want? I convert your input to a data.frame and the split based on your second column. The output of this differs slightly from yours since split
will sort. If you do not want that, you can order the output based on the input.
df <- read.table(textConnection(input[-1]))
alphabets <- split(df$V1, df$V2)
cost <- split(df$V3, df$V2)
# you can do this to reorder how you had it
order <- unique(df$V2)
alphabets[order]
cost[order]
Upvotes: 1