使用特定值提取数据框中的列

时间:2012-01-07 12:52:09

标签: r dataframe

我想将数据框的备用列的值更改为小于1的值。例如

abc 1   ghf 3
def 3   ftr 6
scf 0.2 ugh 1

第二列和第三列的所有小于1的值都应为零。

有没有办法在R?中做到这一点?

2 个答案:

答案 0 :(得分:5)

这实际上有效,并且可能难以改进其简单性:

df[ df<1 ] <- 0

替代方法(但不太紧凑):当与arr.ind=TRUE一起使用时,返回行和列的两列矩阵,其中条件为TRUE。您可以将其与[<-.data.frame一起使用,但需要将其作为数字索引

 idxs <- which(df <1, arr.ind=TRUE)
#Warning messages:
#1: In Ops.factor(left, right) : < not meaningful for factors
#2: In Ops.factor(left, right) : < not meaningful for factors
### Perfectly safe to ignore the warning
 df[ idxs[,1], idxs[,2] ] <- 0
 df
#------------------
   V1 V2  V3 V4
1 abc  1 ghf  3
2 def  3 ftr  6
3 scf  0 ugh  1

答案 1 :(得分:1)

如果您以可以立即使用的格式dput( myData )提供数据,将会有所帮助,其输出可以分配给变量:

> df <- structure(list(V1 = structure(1:3, .Label = c("abc", "def", "scf"                                        
), class = "factor"), V2 = c(1, 3, 0.2), V3 = structure(c(2L, 1L,                                          
3L), .Label = c("ftr", "ghf", "ugh"), class = "factor"), V4 = c(3L,                                      
6L, 1L)), .Names = c("V1", "V2", "V3", "V4"), row.names = c(NA,                                          
-3L), class = "data.frame")

> df
   V1   V2  V3 V4 
1 abc    1 ghf  3
2 def    3 ftr  6 
3 scf  0.2 ugh  1

你说“第二列和第三列的所有值......”但你可能意思是“第二和第四......”。这就是我要做的事情:

> df$V2 <- ifelse( df$V2 < 1, 0, df$V2 )
> df$V4 <- ifelse( df$V4 < 1, 0, df$V4 )
> df
   V1 V2  V3 V4
1 abc  1 ghf  3
2 def  3 ftr  6
3 scf  0 ugh  1

更多请参阅?ifelse,但我认为这应该有所帮助。