Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

dataframe - Replacing values from a column using a condition in R

I have a very basic R question but I am having a hard time trying to get the right answer. I have a data frame that looks like this:

 ind<-rep(1:4,each=24)
 hour<-rep(seq(0,23,by=1),4)
 depth<-runif(length(ind),1,50)

 df<-data.frame(cbind(species,ind,hour,depth))
 df$depth<-as.numeric(df$depth)

What I would like it to select AND replace all the rows where depth < 10 (for example) with zero, but I want to keep all the information associated to those rows and the original dimensions of the data frame.

I have try the following but this does not work.

df[df$depth<10]<-0

Any suggestions?

question from:https://stackoverflow.com/questions/65932560/set-a-column-value-to-na-if-another-column-has-a-specific-string-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
# reassign depth values under 10 to zero
df$depth[df$depth<10] <- 0

(For the columns that are factors, you can only assign values that are factor levels. If you wanted to assign a value that wasn't currently a factor level, you would need to create the additional level first:

levels(df$species) <- c(levels(df$species), "unknown") 
df$species[df$depth<10]  <- "unknown" 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...