Add One Column Below Another in a Data.Frame in R

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

You could also do :

df2 <- data.frame(a = c(df[,"a"], df[,"b"]))

add one column below another one in r

You could do

data.frame(Heading = c(df$`Heading 1`, df$`Heading 2`), value = rep(df$Value, 2))
#> Heading value
#> 1 12 1
#> 2 99 0
#> 3 34 1
#> 4 42 0

Adding data frame below another data frame

With:

library(dplyr)
bind_rows(d1, d2)

you get:

        Dates Actual Predicted
1 24/04/2017 58 NA
2 25/04/2017 59 NA
3 26/04/2017 58 NA
4 27/04/2017 154 NA
5 28/04/2017 117 NA
6 29/04/2017 127 NA
7 30/04/2017 178 NA
8 01/05/2017 NA 68.54159
9 02/05/2017 NA 90.73130
10 03/05/2017 NA 82.76875
11 04/05/2017 NA 117.48913
12 05/05/2017 NA 110.38090
13 06/05/2017 NA 156.53363
14 07/05/2017 NA 198.14819

Or with:

library(data.table)
rbindlist(list(d1,d2), fill = TRUE)

Or with:

library(plyr)
rbind.fill(d1,d2)

Add column in first data frame based upon two columns in second data frame

As you are using the tidyverse you just need a left_join...

dt_b %>% left_join(dt_a %>% rename(Food_b = Food_a))

Joining, by = "Food_b"

Food_b Class
1 Apple Fruit
2 Bread <NA>
3 Onion Vegetable
4 Banana Fruit

The rename is to ensure there is a column with the same name in each dataframe for joining. You can also use a by argument in the left_join to achieve the same thing (dt_b %>% left_join(dt_a, by = c("Food_b" = "Food_a"))).

How to append a single column from 1 data frame to another data frame based on group

We could do a left join

library(dplyr)
df1 %>%
left_join(df2, by = 'document number')

Or using data.table

library(data.table)
setDT(df1)[df2, value := value, on = .(`document number`)]


Related Topics



Leave a reply



Submit