I have a large dataset of samples with descriptors of whether the sample is viable - it looks (kind of) like this, where 'desc' is the description column and 'blank' indicates the sample is not viable:
desc x y z
1 blank 4.529976 5.297952 5.581013
2 blank 5.906855 4.557389 4.901660
3 sample 4.322014 4.798248 4.995959
4 sample 3.997565 5.975604 7.160871
5 blank 4.898922 7.666193 5.551385
6 blank 5.667884 5.195825 5.232072
7 blank 5.524773 6.726074 4.767475
8 sample 4.382937 5.926217 5.203737
9 sample 4.976908 3.079191 4.614121
10 blank 4.572954 4.772373 6.077195
I want to use an if else statement to set the rows with unuseable data to NA. The final data set should look like this:
desc x y z
1 blank NA NA NA
2 blank NA NA NA
3 sample 4.322014 4.798248 4.995959
4 sample 3.997565 5.975604 7.160871
5 blank NA NA NA
6 blank NA NA NA
7 blank NA NA NA
8 sample 4.382937 5.926217 5.203737
9 sample 4.976908 3.079191 4.614121
10 blank NA NA NA
I have tried a for loop, but I'm having trouble getting the for-loop to change all the columns in one loop. My real dataset has 40 columns, so I'd rather not have to process it in separate loops! Here is the code to change one column at a time:
for(i in 1:length(desc)){
if(dat$desc[i] =="blank"){
dat$x[i] <- NA
}
else {
dat$x[i] <- dat$x[i]
}
}
I made the sample data with this script:
desc <- c("blank", "blank", "sample", "sample", "blank", "blank", "blank", "sample", "sample", "blank")
x <- rnorm(10, mean=5, sd=1)
y <- rnorm(10, mean=5, sd=1)
z <- rnorm(10, mean=5, sd=1)
dat <- data.frame(desc,x,y,z)
Sorry if this is a basic question, I've spent all morning looking at forums and haven't been able to find a solution.
Any help is much appreciated!