Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

r - Named List To/From Data.Frame

I'm looking for a quick way to get back and forth between a list of the following format:

$`a`
  [1] 1 2 3
$`b`
  [1] 4 5 6

to/from a data.frame of the following format:

   name x
 1    a 1
 2    a 2
 3    a 3
 4    b 4
 5    b 5
 6    b 6

(Don't really care what the names of the columns are, in this case.)

Here's the data frame used above in R-format:

df <- data.frame(name=c(rep("a",3),rep("b",3)), x=c(1:3,4:6))

Again, I'm looking for two separate operations: one to convert the above data.frame to a list, and another to convert it back to a data.frame.

question from:https://stackoverflow.com/questions/10432993/named-list-to-from-data-frame

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use stack and unstack in base R:

x <- data.frame(a=1:3, b=4:6)

x
  a b
1 1 4
2 2 5
3 3 6

Use stack to from wide to tall, i.e. stack the vectors on top of one another.

y <- stack(x)
y
  values ind
1      1   a
2      2   a
3      3   a
4      4   b
5      5   b
6      6   b

Use unstack to do the reverse.

unstack(y)
  a b
1 1 4
2 2 5
3 3 6

If your data structure is more complicated than you described, stack and unstack may no longer be suitable. In that case you'll have to use reshape in base R, or melt and dcast in package reshape2.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...