I have a dataframe like this
gender <- sample( c("M","F"), 10000, replace=TRUE, prob=c( 0.5, 0.5) )
handed <- sample( c("L","R"), 10000, replace=TRUE, prob=c( 0.2, 0.8) )
data <- data.frame(gender=gender,handed=handed)
I need to replace the first 100 rows which comes from this subset
d <- subset(data,gender=="M" & handed=="R",)
I know the
da <- head(d,n=100)
but I don't know how to replace them in data
.
I want to replace it with:
gender=="F" & handed=="L
I have tried this solution:
Conditions_Seperator<-function(condition){return (unlist(strsplit(condition, "")))}
con<-Conditions_Seperator("MR")
replaceing_con<-Conditions_Seperator("FL")
library(data.table)
setDT(data)[data[, .I[gender==as.character(con[1]) & handed == as.character(con[2])][1:size_to_decrease]],
c('gender', 'handed') := .(as.character(replaceing_con[1]), as.character(replaceing_con[2]))][]
and the output is:
handed
gender L R M
F 6122 95 3592
M 96 95 0
it adds one column to my dataset