mwr
mwr

Reputation: 31

Trying to combine two rows in the same dataframe

I am having some trouble with a code such that a row is weirdly splitting into two, so the top row has some NAs and then the second row has NAs in the opposite columns. It might be an issue with my data being imported, but I was wondering if there is a way to combine the two into one row.

x <- c(1, NA, 3, 4, NA)
y <- c(NA, 2, NA, NA, 5)
df <- t(cbind(x,y))

z <- t(c(1, 2, 3, 4, 5))

  [,1] [,2] [,3] [,4] [,5]
x    1   NA    3    4   NA
y   NA    2   NA   NA    5

[,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5

So basically combine x and y to make z. There is no overlap between my x row and my y row.

Please help!

Upvotes: 0

Views: 40

Answers (3)

Agaz Wani
Agaz Wani

Reputation: 5684

How about using dplyr

library(dplyr)
df <- data.frame(t(coalesce(df[1, ], df[2, ])))

  X1 X2 X3 X4 X5
1  1  2  3  4  5

Upvotes: 0

ThomasIsCoding
ThomasIsCoding

Reputation: 101343

A trick for your case might be using replace + colSums

> t(colSums(replace(df, is.na(df), 0)))
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5

Upvotes: 0

Blue050205
Blue050205

Reputation: 276

How about the following?

z <- c(x[!is.na(x)], y[!is.na(y)])

You will be combining the non-NA values of x and y in a new vector z.

Upvotes: 0

Related Questions