Change column value by row string value in R
Asked Answered
C

2

7

I'm having a problem with a set of data. I want to change the values of a column, only for certain values in the rows of data. My table has this structure:

  Var1   Var2
1   A    High
2   A    High
3   A    High
4   B    High
5   B    High
6   B    High
7   C    High
8   C    Low
9   C    Low
10  C    Low

Now, I want to change the "Var2" values to "Medium", only when Var 1 is C. Thank you for help! :) Alin.

Critter answered 23/11, 2014 at 16:28 Comment(0)
G
8

Assuming d is your data.frame:

d$Var2[d$Var1 == "C"] <- "Medium"
Gebhardt answered 23/11, 2014 at 16:36 Comment(5)
It returs me this message >> Warning message: In [<-.factor(*tmp*, d$Var1 == "C", value = c(1L, 1L, 1L, 1L, : invalid factor level, NA generatedCritter
Make sure Var2 is characterAdin
Yes. It's wasn't character.Critter
.@Gebhardt - Why performing this d[10,"Var1"] <- 0 on above data gives me Warning message: In [<-.factor(*tmp*, iseq, value = 0) : invalid factor level, NA generated. The value instead of being 0 changes to NA for the specific cell. Any suggestions please.Roulers
I tried a similiar approach for my problem here and wrote dat$participant[dat$date== "2020-06-07_12h33.46.880"] <- "101" But it didn't work. What am I missing? date and participant are characters #62377488Dharma
M
1

try

d$Var2[d$Var1 == "C", ] <- "Medium"

There has to be a comma after the condition. This is a R-specific thing.

Midwife answered 11/1, 2021 at 16:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.