Home > other >  R replace multiple rows in dataframe
R replace multiple rows in dataframe

Time:10-21

I have a dataframe as follows:

df = data.frame(n=c(1, 2, 3), m=c(4, 5, 6))

which yields the following result:

    n m
  1 1 4
  2 2 5
  3 3 6

Now say I want to replace the first two rows with a vector c(1, 2). I tried to do this:

df[1:2,] = c(1, 2)

But this yields the result

    n m
  1 1 1
  2 2 2
  3 3 6

But what I want is

    n m
  1 1 2
  2 1 2
  3 3 6

I tried setting c(1, 2) to a matrix that is 1x2 to see if that would replace the rows "row first" instead of "column first" but that didn't work (still replaced "column first"). Neither did changing the matrix dimensions to 2x1. I then tried making c(1, 2) into a dataframe and replacing the rows using the dataframe like so df[1:2,] = data.frame(c(1, 2)), but that still yielded the undesired result. Same thing if I replace the dataframe with it's transpose using t(). Is there any way to replace rows in a dataframe row first? Obviously, if I only select one row at a time such as df[1,] = data.frame(c(1, 2)) it works just fine giving me

    n m
  1 1 2
  2 2 5
  3 3 6

However, I want to do this for several rows at once. Is there any way to do this?

CodePudding user response:

You need a list in this case:

> df[1:2,] <- list(1, 2)
> df
  n m
1 1 2
2 1 2
3 3 6
> 

It would get assigned differently:

> list(1, 2)
[[1]]
[1] 1

[[2]]
[1] 2

> c(1, 2)
[1] 1 2
> 

A more concrete example of what it would do in the background:

> list(n=1, m=2)
$n
[1] 1

$m
[1] 2

> 

CodePudding user response:

Try

df[1:2, ] <- rep(c(1, 2), each = 2)

Change each to the number of rows you wanna replace.

CodePudding user response:

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

df <- data.frame(n=c(1, 2, 3), m=c(4, 5, 6))
df
#>   n m
#> 1 1 4
#> 2 2 5
#> 3 3 6

df %>% mutate(
  n = ifelse(row_number() %in% c(1,2), 1, n),
  m = ifelse(row_number() %in% c(1,2), 2, m)
)
#>   n m
#> 1 1 2
#> 2 1 2
#> 3 3 6

Created on 2021-10-20 by the reprex package (v2.0.1)

  • Related