How do I change a value in two duplicate rows so the rows become unique

Viewed 86

So my starting data frame looks like this:

Country    Value 1     Value 2
Sudan       1             3
USA         2             2
Russia      2             1

I am trying to get to this:

Country    Value 1     Value 2
Sudan       1             3
South Sudan 1             3
USA         2             2
Russia      2             1

So I want to copy the Sudan row and change only one of the values to South Sudan.

I know how to get to this:

Country    Value 1     Value 2
Sudan       1             3
Sudan       1             3
USA         2             2
Russia      2             1

But I do not know what to do next.

2 Answers

We can replicate the first row and assign the second element of 'Country' to 'South Sudan' in base R (no packages needed)

df2 <- df1[c(1, seq_len(nrow(df1))),]
row.names(df2) <- NULL
df2$Country[2] <- "South Sudan"

-output

df2
#      Country Value1 Value2
#1       Sudan      1      3
#2 South Sudan      1      3
#3         USA      2      2
#4      Russia      2      1

data

df1 <- structure(list(Country = c("Sudan", "USA", "Russia"), Value1 = c(1L, 
2L, 2L), Value2 = 3:1), class = "data.frame", row.names = c(NA, 
-3L))

Let's assume there are 2 rows of Sudan

df <- read.table(text = "Country    Value1     Value2
Sudan       1             3
USA         2             2
Russia      2             1
Sudan       4             7", header =T)

Now do this

df %>% add_row(Country = "South Sudan", df %>% filter(Country == "Sudan") %>% select(-Country))

      Country Value1 Value2
1       Sudan      1      3
2         USA      2      2
3      Russia      2      1
4       Sudan      4      7
5 South Sudan      1      3
6 South Sudan      4      7
Related