0

I have a long data frame in R with a column called "Well." Each well occurs more than once in that column. For a small subset of those wells, I want to add a value to an empty column called "Trypan."

So my df looks something like this, but very long.

Well Trypan
A12 NA
B12 NA
C12 NA
... NA
A12 NA
B12 NA
C12 NA

I want to assign a value in the trypan column that is the same for every well called A12. I don't want to write a whole vector or make a new df and attach/melt it though, that's a pain.

I want to do something as simple as "if well = A12, Trypan = 90." But I cannot figure out that syntax!

I have in fact tried googling this but it seems like other people are asking different questions that I cannot apply to my problem. My apologies for this very basic question.

ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81

2 Answers2

1

Just create a logical vector with == and use that index to assign 90 to those rows in 'Trypan'

df1$Trypan[df1$Well == "A12"] <- 90

-ouput

    Well Trypan
1  A12     90
2  B12     NA
3  C12     NA
4  A12     90
5  B12     NA
6  C12     NA

data

df1 <- structure(list(Well = c("A12", "B12", "C12", "A12", "B12", "C12"
), Trypan = c(90, NA, NA, 90, NA, NA)), row.names = c(NA, -6L
), class = "data.frame")
akrun
  • 874,273
  • 37
  • 540
  • 662
1

You can try

transform(
  df,
  Trypan = replace(Trypan, Well == "A12", 90)
)

which gives

  Well Trypan
1  A12     90
2  B12     NA
3  C12     NA
4  A12     90
5  B12     NA
6  C12     NA

Data

> dput(df)
structure(list(Well = c("A12", "B12", "C12", "A12", "B12", "C12"
), Trypan = c(90, NA, NA, 90, NA, NA)), row.names = c(NA, -6L
), class = "data.frame")
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81