I would like to replace a single value in a dataframe by name:
df <- data.frame(samples= c('sample_2', 'sample_2', 'sample_3', 'sample_3', 'sample_4', 'sample_4'), size=rnorm(3), group= c('group_1', 'group_1','group_1','group_2','group_2','group_2'))
Is there a simple way to replace the value in the field 'size' in line 4 using a combination of the 'samples' and 'group' names (e.g. using dplyr)? I don't want to use numerical indexing of rows and columns).
CodePudding user response:
library(dplyr)
df %>%
mutate(size = ifelse(samples == "sample_3" & group == "group_2", 999, size))
Where 999
is the value you want to replace.
This gives us:
samples size group
1 sample_2 -0.5217487 group_1
2 sample_2 0.2443456 group_1
3 sample_3 -0.4490446 group_1
4 sample_3 999.0000000 group_2
5 sample_4 0.2443456 group_2
6 sample_4 -0.4490446 group_2
CodePudding user response:
In addition to Matt's answer, here's how you could do it with base R or data table.
Base R
df$size[df$samples == "sample_3" & df$group == "group2"] = 999
data.table
setDT(df)
df[samples == "sample_3" & group == "group_2", size := 999]