Biostats
Biostats

Reputation: 51

How to replace values for a group of columns and a single row in a data frame?

I have a data frame as follows -

df <- cbind(c("a","b","c","d","e"),c(1,2,3,4,5),c(6,8,10,12,19))
colnames(df) <- c("c1","c2","c3")

I want to replace the values of 3rd row in column 2 and 3 to 7 and 9, respectively. I used the following code

df <- df%>%replace(list = df[,c(2:3)], values = c(7,9))

But it is not working. Could someone guide me please where I am wrong and how I can get the desired result?

Upvotes: 0

Views: 159

Answers (2)

akrun
akrun

Reputation: 886938

We can pass the list as row/column indexing in a matrix and cbind creates a matrix

library(dplyr)
df <- df %>%
     replace(cbind(3, 2:3), c(7,9))

-output

df
    c1  c2  c3  
[1,] "a" "1" "6" 
[2,] "b" "2" "8" 
[3,] "c" "7" "9" 
[4,] "d" "4" "12"
[5,] "e" "5" "19"

Upvotes: 3

Vin&#237;cius F&#233;lix
Vin&#237;cius F&#233;lix

Reputation: 8811

A R Base solution would be:

  df[3,2:3] <- c(7,9)

Upvotes: 2

Related Questions