-1

I have successfully added a new blank row 1 “24727.2” but I want to duplicate the values from columns 2:11 named 2009:2018 in row [5] “state=24727” to row 1. Then I want to change the values for columns less than 2016 to NA only in row 1. I can’t seem to get the duplicate/replicate data to copy/paste into row 1 “24727.2” using ifelse, mutate_at or mutate_each, replace_na(), or summarise. Any help or assistance is appreciated.

library(dplyr)
library(tidyr)
library(tibble)
temp <- data %>% 
  group_by(year, state) %>%
  summarise(mean.var3 = mean(var3)) %>%
  spread(year, mean.var3) %>%
  do(add_row(., state=24727.2, .before=1)) %>%
print(temp)

Tibble

medjenny
  • 11
  • 1
  • Please show a small example with `dput` – akrun Aug 28 '20 at 21:41
  • @akrun- If you click on "Tibble" you can see the output. – medjenny Aug 28 '20 at 22:36
  • yes, but looks like an image to me. It cannot be used for testing purposes – akrun Aug 28 '20 at 22:37
  • 1
    Please add data using `dput` and show the expected output for the same. Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269). – Ronak Shah Aug 29 '20 at 02:53
  • @Ronak Shah: I appreciate your willingness to review my question but I am unable to provide the necessary code and datasets to give a reproducible example at this time. However, akrun was very helpful in providing two scenarios I could use to do what I need to do. – medjenny Aug 29 '20 at 03:31

1 Answers1

0

If we are only interested in the first row, we can use replace

library(dplyr)
temp <- temp %>%
           mutate(across(where(is.numeric), ~ replace(., 1, .[2])))

Or with base R

temp[1, -1] <- temp[2, -1]
akrun
  • 874,273
  • 37
  • 540
  • 662
  • in the first example, I am getting an error code for unknown function for "across" and "where". I was able to solve the "across" error code by changing it to spread(), but am still looking for the replacement for "where". For the second example, it works exactly how I want it to. I do have a question about it though. In [1,-1] I am assuming that the -1 in the y spot is essentially telling it to copy everything on the row except for the first column. Am I correct in that assumption? – medjenny Aug 28 '20 at 23:17
  • @medjenny it is from the new version of `dplyr` if you have version that is < 1.0.0, then it may get error – akrun Aug 28 '20 at 23:18
  • @medjenny if your dplyr version is old, try `temp %>% mutate_if(is.numeric, ~ replace(., 1, .[2]))` – akrun Aug 28 '20 at 23:19