Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I would like to fill in the missing values in one column in a table. In the column combName the values should go up to 20-400 and continue with 21-1 to 21-400 and so on. For every missing value a new row should be created with the value in the right enumerated order and 0 in all other fields of the row.

   combName sumLength RootID
   <chr>        <dbl>  <int>
 1 20-1          8.05      1
 2 20-2          4.61      1
 3 20-3         14.5       1
 4 20-8          2.29      1
 5 20-10        14.7       1
 6 20-11        23.0       4
 7 20-12        17.0       5
 8 20-13        66.9      14
 9 20-14        39.1       9
10 20-15        12.5       6
# ... with 1,099 more rows

Are there any ideas how this is possible?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
396 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can achieve this with the help of functions from tidyr library.

Divide combName into two columns splitting on '-'. For every value in col1 create rows from 1 to 400 in col2 and finally combine col1 and col2 into one column again.

library(tidyr)

df %>%
  separate(combName, c('col1', 'col2'), sep = '-', convert = TRUE) %>%
  complete(col1, col2 = 1:400, fill = list(sumLength = 0, RootID = 0)) %>%
  unite(combName, col1, col2, sep = '-')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...