1

Ok this should be simple and I am aware of many questions similar to this that have been answered but none of the answers are working for my data.

Here is some quick example data to illustrate my point:

Soil <- c("Organic - 10", "Organic - 12", "Sand - 6", "Silt - 6", "Silt - 6")
Value1 <- c(2, 5, 1, 4, 6)
Value2 <- c(45, 21, 776, 2, 6)
X03 <- c(4, 23, 45, 12, 23)
X04 <- c(56, 2, 7, 34, 65)

DF <- data.frame(Soil, Value1, Value2, X03, X04)

Basically what I want to do is replace the values of X02 and X03 with 0 for the rows where Soil is "Organic".

My initial thought was to do the following:

# create index of the columns in whcih values are to be changed
index <- grep("^X0", colnames(DF))
# Use ifelse statement to change values conditionally
DF[,c(index)] <- ifelse(grepl("^Organic", DF$Soil), 0, DF[index])

This however gives the following warning and replaces all values with 0 in X03 and X04:

Warning message:
In `[<-.data.frame`(`*tmp*`, , c(index), value = list(0, 0, c(4,  :
  provided 5 variables to replace 2 variables

Any ideas appreciated.

1 Answer 1

1

Try

DF[grepl("^Organic", DF$Soil),index]<-0
Sign up to request clarification or add additional context in comments.

1 Comment

Simple, elegant and best it works! One day I'll be able to figure these things out first time by myself! Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.