使用 R 中的条件替换列中的值 [英] Replacing values from a column using a condition in R
问题描述
我有一个非常基本的 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)
我希望它选择并替换 depth <的所有行10
(例如)为零,但我想保留与这些行相关的所有信息以及数据框的原始维度.
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
有什么建议吗?
推荐答案
# 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"
这篇关于使用 R 中的条件替换列中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!