Home > Software engineering >  Combine every two rows of data in R
Combine every two rows of data in R

Time:09-22

I have a csv file that I have read in but I now need to combine every two rows together. There is a total of 2000 rows but I need to reduce to 1000 rows. Every two rows is has the same account number in one column and the address split into two rows in another. Two rows are taken up for each observation and I want to combine two address rows into one. For example rows 1 and 2 are Acct# 1234 and have 123 Hollywood Blvd and LA California 90028 on their own lines respectively.

CodePudding user response:

It can be fairly simple with data.table package:

# assuming `dataset` is the name of your dataset, column with account number is called 'actN' and column with adress is 'adr'
library(data.table)
dataset2 <- data.table(dataset)[,.(whole = paste0(adr, collapse = ", ")), by = .(adr)]

CodePudding user response:

Using the tidyverse, you can group_by the Acct number and summarise with str_c:

library(tidyverse)
df %>%
  group_by(Acct) %>%
  summarise(Address = str_c(Address, collapse = " "))
# A tibble: 2 × 2
   Acct Address                               
  <dbl> <chr>                                 
1  1234 123 Hollywood Blvd LA California 90028
2  4321 55 Park Avenue NY New York State 6666

Data:

df <- data.frame(
  Acct = c(1234, 1234, 4321, 4321),
  Address = c("123 Hollywood Blvd", "LA California 90028", 
              "55 Park Avenue", "NY New York State 6666")
)
  • Related