Dagman
Dagman

Reputation: 81

R replace multiple rows in dataframe

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?

Upvotes: 4

Views: 1340

Answers (3)

danlooo
danlooo

Reputation: 10627

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)

Upvotes: 0

Hann Shaw
Hann Shaw

Reputation: 91

Try

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

Change each to the number of rows you wanna replace.

Upvotes: 0

U13-Forward
U13-Forward

Reputation: 71580

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

> 

Upvotes: 5

Related Questions