Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 416
buhtz Avatar asked Nov 27 '16 15:11

buhtz


People also ask

How do I add one column to another column in R?

To add a new column to a dataframe in R you can use the $-operator. For example, to add the column “NewColumn”, you can do like this: dataf$NewColumn <- Values . Now, this will effectively add your new variable to your dataset.

How do I add Dataframe below another Dataframe in R?

To append data frames in R, use the rbind() function. The rbind() is a built-in R function that can combine several vectors, matrices, and/or data frames by rows. To join two data frames (datasets) vertically, use the rbind() function.

How do I append a column to a Dataframe in R?

1 Adding new columns. You can add new columns to a dataframe using the $ and assignment <- operators. To do this, just use the df$name notation and assign a new vector of data to it. As you can see, survey has a new column with the name sex with the values we specified earlier.

How do I stack two columns in R?

Method 1: Using stack method The cbind() operation is used to stack the columns of the data frame together. Initially, the first two columns of the data frame are combined together using the df[1:2]. This is followed by the application of stack() method applied on the last two columns.


2 Answers

You could also do :

df2 <- data.frame(a = c(df[,"a"], df[,"b"]))
like image 153
User2321 Avatar answered Sep 17 '22 13:09

User2321


You can use pivot_longer() from tidyr package.

library(dplyr)
set.seed(1)
df <- data.frame(a=sample(1:10), b=sample(1:10))
pivot_longer(df, a:b)


# A tibble: 20 x 2
   name  value
   <chr> <int>
 1 a         3
 2 b         3
 3 a         4
 4 b         2
 5 a         5
 6 b         6
 7 a         7
 8 b        10
 9 a         2
10 b         5
11 a         8
12 b         7
13 a         9
14 b         8
15 a         6
16 b         4
17 a        10
18 b         1
19 a         1
20 b         9
like image 29
Tiago Olivoto Avatar answered Sep 17 '22 13:09

Tiago Olivoto