Home > Back-end >  Replacing row values in R data frame based on other row value in same column
Replacing row values in R data frame based on other row value in same column

Time:11-03

I need to update values in a specific row of a data frame based on values in the same columns but in a different row.

Name c1  c2  c3  c4
A    1   2   3   4
B    0   0   0   0
C    1   1   1   1

I would like to apply a function to the values in row A, columns c2, c3, and c4 and replace the values in row B, columns c2, c3, and c4 with the result.

For example, if the function was 2x, then the resulting data frame would be

Name c1  c2  c3  c4
A    1   2   3   4
B    0   4   6   8
C    1   1   1   1

CodePudding user response:

You may try

dummy <- read.table(text = "Name c1  c2  c3  c4
A    1   2   3   4
B    0   0   0   0
C    1   1   1   1", header = T)

dummy[dummy$Name =="B", c("c2","c3","c4")] <- 2 * dummy[dummy$Name == "A", c("c2","c3","c4")]

dummy

  Name c1 c2 c3 c4
1    A  1  2  3  4
2    B  0  4  6  8
3    C  1  1  1  1

CodePudding user response:

Does this work, where row is the one that you want to change in dataframe and iprow is the one you want to multiple with x.

df
  Name c1 c2 c3 c4
1    A  1  2  3  4
2    B  0  0  0  0
3    C  1  1  1  1

myfunc <- function(df, row, iprow, x){
          df[row, 2:ncol(df)] = df[iprow, 2:ncol(df)] * x
          df
}

myfunc(df, 2, 1, 2)
  Name c1 c2 c3 c4
1    A  1  2  3  4
2    B  2  4  6  8
3    C  1  1  1  1

CodePudding user response:

Define subset, assign multiplied 1st to 2nd row.

s <- c('c2', 'c3', 'c4')
d[2, s] <- d[1, s] * 2 
d
#   Name c1 c2 c3 c4
# 1    A  1  2  3  4
# 2    B  0  4  6  8
# 3    C  1  1  1  1

Data:

d <- structure(list(Name = c("A", "B", "C"), c1 = c(1L, 0L, 1L), c2 = c(2L, 
0L, 1L), c3 = c(3L, 0L, 1L), c4 = c(4L, 0L, 1L)), class = "data.frame", row.names = c(NA, 
-3L))
  •  Tags:  
  • r
  • Related