0

I've googled a bunch and could find an answer anywhere but that maybe that I couldn't explain it well in few words.

Coffee|     |Steve

Coffee| Cup |     |

Turkey| Fork|     |

      |Fork |Mike

I'd like tho take the data in these four rows and consolidate it into two rows so it is displayed.

Coffee|Cup|Steve

Turkey|Fork|Mike

I'd appreciate any help. I am brand new to code. I am saw it being benefical and quicker at work in the long run.

Thanks

RHertel
  • 23,412
  • 5
  • 38
  • 64
  • 3
    Can you post sample data? Please edit **the question** with the output of `dput(df)`. Or, if it is too big with the output of `dput(head(df, 20))`. (`df` is the name of your dataset.) – Rui Barradas Jul 25 '18 at 15:55
  • Sample Data is unfortunately not possible – Michael Klepfer Jul 25 '18 at 16:03
  • 1
    [This quesiton](https://stackoverflow.com/questions/45515218/combine-rows-in-data-frame-containing-na-to-make-complete-row) looks similar and might be helpful. – Evan Jul 25 '18 at 16:49
  • 1
    If you aren't sure how to add sample data to your question, [this SO question](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) has great suggestions and examples specific to R – Jan Boyer Jul 25 '18 at 17:05

2 Answers2

1

Using library(tidyverse) and making bold assumptions about your data set:

df <- data.frame(food = c("Coffee","Coffee","Turkey", NA), 
             utensil = c(NA, "Cup", "Fork", "Fork"), 
             name = c("Steve", NA, NA, "Mike"))
df <- df %>%
  group_by(food) %>%
  arrange(utensil) %>%
  fill(utensil) %>%
  group_by(utensil) %>%
  arrange(food) %>%
  fill(food) %>%
  drop_na()
Eric Krantz
  • 1,854
  • 15
  • 25
0

I think it's best to decompose the table into a list, remove NA values, then take unique. Then you can just convert back to a data frame. I am using read_r to make a data frame here, but the rest is Base R.

myTab <- readr::read_csv("h1,h2,h3
Coffee,,Steve
Coffee,Cup,
Turkey,Fork,
,Fork,Mike")

myTab

## # A tibble: 4 x 3
##   h1     h2    h3   
##   <chr>  <chr> <chr>
## 1 Coffee NA    Steve
## 2 Coffee Cup   NA   
## 3 Turkey Fork  NA   
## 4 NA     Fork  Mike 

myTab <- lapply(myTab, na.omit)
myTab <- lapply(myTab, as.character)
myTab <- lapply(myTab, unique)

myTab <- data.frame(myTab)

myTab

##      h1   h2    h3
## 1 Coffee  Cup Steve
## 2 Turkey Fork  Mike
JMT2080AD
  • 1,049
  • 8
  • 15