Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

add one column below another in a data.frame in R

Not sure if I used the correct english words in the subject to describe what I need.

See this example

df <- data.frame(a=sample(1:10), b=sample(1:10))
df
    a  b
1   2  9
2   5  8
3  10  1
4   3  7
5   8  4
6   6 10
7   9  5
8   7  6
9   1  3
10  4  2

I want to take b column at put it below a as 10 new rows.

    a
1   2
2   5
3  10
4   3
5   8
6   6
7   9
8   7
9   1
10  4
11  9
12  8
13  1
14  7
15  4
16 10
17  5
18  6
19  3
20  2

I found examples with rbind but couldn't find out how to use it in my situation.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

We can use unlist to create a vector and then wrap it with data.frame to create a new dataset.

d1 <- data.frame(a=unlist(df, use.names = FALSE))
d1
#    a
#1   2
#2   5
#3  10
#4   3
#5   8
#6   6
#7   9
#8   7
#9   1
#10  4
#11  9
#12  8
#13  1
#14  7
#15  4
#16 10
#17  5
#18  6
#19  3
#20  2

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...