0

I want to create a df in R with two variables, they have different number of rows. This is an abstract example: I want to match a 3 to "Fail" (without writing in manually, I know that I could just write the 3 in a on the third place). So first assign 3 to Fail, than match 1 to Test, 2 to Test, 4 to Success and 5 to Test by skipping Fail.

a <- c(1,2,4,5)
b <- c("Test", "Test", "Fail", "Success", "Test")
data.frame(a,b)

So the following steps would be important:

1st: find string "Fail": assign a certain value to it (here 3)

2nd: create a df with a and b

3rd: final result should look like this:

a b
1 Test
2 Test
3 Fail
4 Success
5 Test
Sotos
  • 51,121
  • 6
  • 32
  • 66
dlwhch
  • 157
  • 7

2 Answers2

1
idx <- which(b == "Fail")
a <- append(a, idx, after = idx - 1)
#[1] 1 2 3 4 5

data.frame(a, b)
  a       b
1 1    Test
2 2    Test
3 3    Fail
4 4 Success
5 5    Test
Maël
  • 45,206
  • 3
  • 29
  • 67
  • Thanks that's what I wanted, does this work for multiple Rows as well? For example if I would like to have "Test" == 1 always? In this case a would be something like: a=c(3,4). 3 for Fail and 4 for Success – dlwhch May 13 '22 at 13:51
  • With a few tweaks it should work yes – Maël May 13 '22 at 14:02
0

You don't need to create both vectors. If you are going with indexes, you can just do,

data.frame(a = seq_along(b), b = b)

  a       b
1 1    Test
2 2    Test
3 3    Fail
4 4 Success
5 5    Test
Sotos
  • 51,121
  • 6
  • 32
  • 66