R - Merging two columns so to get rid of NA entries

This question already has an answer here:

  • Merging two columns into one in R 5 answers

I have two columns of data consisting number and NA entries. There is no row in which both columns have NA as that row's entry, but the columns both have NA as entries for some rows. I would like to make a new vector. If one of my two initial columns has a numerical value, I would like the new vector's entry for that row to be that numerical value. So going from this:

c1 c2 1 NA 2 NA NA 3

to this:

c1 c2 c3 1 NA 1 2 NA 2 NA 3 3

I can do this with for loops:

for (i in 1:length(c1)) { if (!is.na(c1[i])) { c3[i] <- c1[i] } else { if (!is.na(c2[i])) { c3[i] <- c2[i] } } }

But I am assuming that there is a cleaner way to do it that takes advantage of R's features. Thank you!

-------------Problems Reply------------

You could use either pmax/pmin

df1$c3 <- do.call(pmax, c(df1, na.rm=TRUE))
df1
# c1 c2 c3
#1 1 NA 1
#2 2 NA 2
#3 NA 3 3

Or max.col on the logical matrix (!is.na(df1)) to get the column index of maximum value for each row, and cbind with row index (1:nrow(df1)) to extract the elements.

df1$c3 <- df1[cbind(1:nrow(df1),max.col(!is.na(df1)))]

data

df1 <- structure(list(c1 = c(1L, 2L, NA), c2 = c(NA, NA, 3L)),
.Names = c("c1",
"c2"), class = "data.frame", row.names = c(NA, -3L))

Category:r Views:0 Time:2018-02-11
Tags:

Related post

  • to merge two columns in a csv file 2010-07-08

    merge two columns in a csv file --------------Solutions------------- Here is an example, dont know your delimiter. if you want to write it to the same file you have to buffer the whole file first, modify the rows, then write it back to the same file.

  • How do I merge two columns in a DataSet? 2009-01-19

    Previously I've asked about inserting a column into a dataset. I now have a similar question...namely merging two or more columns into a single column. Lets say I have the following data set: DataSet ds = new DataSet(); ds.Tables.Add(new DataTable())

  • how to merge two column in one column 2013-10-31

    hi friends I would like to merge two column in one column for example City Village City A B A C D C E F E I need the query to have all these three in one column with distinct values such as All Hotel A B C D E F that what i want to have in the output

  • keep getting error code 8024001b for two weeks now cant get rid of it 2014-07-14

    keep getting error code 8024001b for two weeks now cant get rid of it and saying try again --------------Solutions------------- Hi, When exactly do you get the error message? I would suggest you to try the steps from the following link: Windows Updat

  • Get rid of duplicate entries in autocomplete 2012-04-10

    I am having difficulty getting rid of duplicate entries which are showing up in autocomplete. The autocomplete is generated dynamically from a database. This is the code which is being used for the autocomplete in the control: public ActionResult Aut

  • How do I get rid of an entry on the drop-down list when I attempt to sign-in? 2012-08-18

    How do I get rid of an entry on the drop-down list when I attempt to sign-in? I mistakenly typed my password next to my email address; now the password shows up as part of my hotmail address as another option when I sign in??!! I tried the suggestion

  • merge two columns into one column and get unique 2012-01-18

    I have two columns in a table. I need to merge these two columns into 1 column, while making sure all the values in the resulting column are unique (no repetition of the IDs) ex: ChildCard PrimaryCard 123456 123456 123450 123456 123446 123446 123456

  • How to merge two columns of JTable 2011-04-12

    I am retriving data from database.TableName:Contacts. There are two fields of this table.First_Name and Last_Name. I want to merge these two columns and want one column of JTable as Full Name.I've tried to create concat sql query,which was: String qu

  • How to merge two columns in R with a specific symbol? 2011-04-05

    I have a table read in R. As follows: column1 column2 A B What is the command line need to be use to match two columns together as follows? Column 3 A_B --------------Solutions------------- I'm a bit unsure what you mean by "merge", but is this what

  • Merging two columns of fields in MySQL 2011-09-29

    Possible Duplicate: Merge date from one datetime and time from another datetime How can I physically merge two MySQL column/fields into one column/field without losing any data on it Specifically I will be combining a DATE and TIME column/field thank

  • merge two columns and sorting in SQL CE 2011-11-02

    I have these two columns to be merged into Column3 and sorted like the way below (first element from column1 then second element from column2 and so on) by using SQLCE in C#. Column1 Column2 ------- ------- pear banana apple pineapple . . . . . . Col

  • Merging Two Columns in Pivot Table 2014-07-10

    I am trying to reformat my pivot table. Currently, there are two columns called closed and completed, which essentially represent the same thing. I would like to merge these two columns together. How can I do this? --------------Solutions------------

  • Not able to merge two columns in SQL Server while printing 2011-06-11

    I want to print two columns of a table in a desired format. I tried with the below format but it's giving error saying Error converting data type varchar to bigint. This is my query: Select ClassID + ' .' + ClassSectionID AS Class from ClassSectionMa

  • How do I get rid of Duplicate Entries With Unique IDs in MS Access 2003? 2010-05-05

    I'm working on an MS Access Database with tons of duplicate entries. The problem is that there is a table of students, and sometimes instead of just updating a certain student's information, someone would just add the student in again with a differen

  • how do I get rid of RunDLL [email protected] viurs without purchasing fix it software? 2013-03-31

    Error in C:\Windows|system32\spool\DRIVERS\X64\3\LXCGtime.dll................anyone know what this is & how do I get rid of it. --------------Solutions------------- Hi, Part of Lexmark Printer Drivers. If you have or HAD a Lexmark Printer then re

  • how do u get rid of registry entries when it says cannot delete in reg mon? 2012-02-13

    hi, my copy of gta4 wont run because this prog secur rom has flipped it's lid.i've contacted support and they sent me this program to get rid of these license codes or whatever that are the problem but it dosent it has the same problem as the game wh

  • SQL server database merging two columns? 2011-08-26

    I have a table emp as follows: empid empname homephone homeadd workphone workadd 1 ron 209999000 1234st 222222 unit-20c 2 dd 2222333 unit56c 3444 bloor I would like to create a temp table as follows: empid empname phone add 1 ron 209999000 1234st 1 r

  • Winform Merging two columns 2009-12-29

    HI, I want to create a datagridview in a form with 4 columns basically which has only 2 column headers, ie i want to merge only the column headers of 2 columns. Thanks in advance --------------Solutions------------- pls, check if code from this SO qu

  • How does plyr merge two columns of different data.frames with same names but different values 2011-05-28

    While merging 3 data.frames using plyr library, I encounter some values with the same name but with different values each in different data.frames. How does the do.call(rbind.fill,list) treat this problem: by arithmetic or geometric average? --------

  • Merge two columns data into one column in another first table 2011-08-11

    I want a query, in my case table1 and table 2 have different structure but id is the common field all i want is find the way to display the data from table1 and table2. on ===> id table1 = id table2 into table1 For example dbo.Personal_details hav

  • LINQ2SQL: how to merge two columns from the same table into a single list 2011-11-24

    this is probably a simple question, but I'm only a beginner so... Suppose I have a table containing home-work locations (cities) certain people use. Something like: ID(int), namePerson(string), homeLocation(string), workLocation(string) where homeLoc

  • Need to merge two columns so I can GROUP BY in same table 2011-06-16

    I'm trying to make the Conversations Overview page for a messaging system in PHP/MySQL. Basically, it would look like the iPhone's Text/SMS overview page. Messages grouped by the other users you have sent or received messages from. It should show the

  • How to merge two column which are already exist in one datatable? 2012-04-05

    I have one datatable. In that table I have columns named [Total Day], [Present day], and [leave]. Data are as follows: [Total Day], [Present day], [leave] 30 25 5 30 26 4 Now i want to concatenate those three columns in one another column. I want out

  • MySQL how do I merge two columns into one, only showing distinct values? 2012-03-07

    I have the following table Table: Times timeid time 1 10 2 11 3 3 Table: Counts countId timeID numberCounts times 1 1 1 0 2 2 3 11 2 2 3 12 3 2 3 13 4 3 1 0 Query I'm using SELECT t.time AS "Start Channel", c.times AS Lapse FROM Times t JOIN Count c

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.167 (s). 11 q(s)