使用R中的条件替换列中的值 [英] Replacing values from a column using a condition in R

查看:599
本文介绍了使用R中的条件替换列中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常基本的R问题,但我很难找到正确的答案。我有一个数据框,如下所示:


 种类<  - ABC
ind< -rep(1:4,each = 24)
小时< -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)


我想要选择并替换深度为< ; 10(例如)为零,但我想保留与这些行相关联的所有信息和数据框的原始维度。



我尝试以下操作这不行。


  df [df $ depth< 10]< -0 


任何建议?

解决方案

 #将10以下的深度值重新分配到零
df $ depth [df $ depth< 10]< - 0

(对于这些因素的列,您只能分配因子级别的值,如果要分配一个当前不是因子水平的值,您需要先创建附加级别:

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

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:

species<-"ABC"
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 is < 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?

解决方案

# 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆