W
W
wolverine7772019-12-17 01:23:51
R
wolverine777, 2019-12-17 01:23:51

How to "fill" the names in a column with already known names from the table?

Hello, I have a table like this:

id
gene0   1   2   3
gene1   0   0   5
gene2   6   8   0
gene3   5   5   5
        0   0   5
        1   2   3

but, as you can see, at the bottom there are repeating rows but for which there is no name.
I would like to get such a table, based on the fact that gene1 0 0 5andgene0 1 2 3
id
gene0   1   2   3
gene1   0   0   5
gene2   6   8   0
gene3   5   5   5
gene1   0   0   5
gene0   1   2   3

I was advised this:
df %>%
 group_by_at(-1) %>%
 fill(id)

but, although there are no errors, the rows are not filled.
Maybe you shouldn't use R at all?
Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
BkmzSpb, 2020-01-17
@BkmzSpb

I don’t know how relevant this is, but here is a working version (I don’t pretend to be optimal):

library(tidyverse)
library(vctrs)
con <- textConnection(
"gene0   1   2   3
gene1   0   0   5
gene2   6   8   0
gene3   5   5   5
NA      0   0   5
NA      1   2   3
NA      0   0   5
NA      6   8   0
NA      5   5   5
NA      0   0   5
NA      1   2   3")


read.table(con) %>% 
    as_tibble %>%
    set_names(vec_c("id", "A", "B", "C")) -> src_table

close(con)

src_table %>%
    filter(!is.na(id)) -> template

src_table %>%
    select(-id) %>%
    left_join(template, by = vec_c("A", "B", "C")) %>%
    select(id, everything()) -> result

print(src_table)
#> # A tibble: 11 x 4
#>    id        A     B     C
#>    <fct> <int> <int> <int>
#>  1 gene0     1     2     3
#>  2 gene1     0     0     5
#>  3 gene2     6     8     0
#>  4 gene3     5     5     5
#>  5 <NA>      0     0     5
#>  6 <NA>      1     2     3
#>  7 <NA>      0     0     5
#>  8 <NA>      6     8     0
#>  9 <NA>      5     5     5
#> 10 <NA>      0     0     5
#> 11 <NA>      1     2     3
print(result)
#> # A tibble: 11 x 4
#>    id        A     B     C
#>    <fct> <int> <int> <int>
#>  1 gene0     1     2     3
#>  2 gene1     0     0     5
#>  3 gene2     6     8     0
#>  4 gene3     5     5     5
#>  5 gene1     0     0     5
#>  6 gene0     1     2     3
#>  7 gene1     0     0     5
#>  8 gene2     6     8     0
#>  9 gene3     5     5     5
#> 10 gene1     0     0     5
#> 11 gene0     1     2     3

Created on 2020-01-17 by the [reprex package]( https://reprex.tidyverse.org) (v0.3.0)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question