每行增加(或不增加)一列的内容

时间:2014-09-12 14:23:48

标签: r syntax-error rows apply

我有一个混合类的数据框:

  • ratio(因子或数字)
  • other(无论如何)
  • error.counter(整数)

      ratio other error.counter
    1  1.00     1             0
    2  2.00     2             0
    3  1.33     3             0
    4  1.00     4             0
    5  0.66     1             0
    6  1.00     2             0
    

我的最终目标是在error.counter大于1时增加ratio

首先,尝试输出相关的行:

> apply(d, 1, function(x) if (as.numeric(x$ratio) > 1.00) paste(x))
Error in x$ratio : $ operator is invalid for atomic vectors

我不明白这个错误......

虽然,它使用双括号的等效语法有效:

> apply(d, 1, function(x) if (as.numeric(x[["ratio"]]) > 1.00) paste(x))
$`1`
NULL

$`2`
[1] "2" "2" "0"

$`3`
[1] "1.33" "3"    "0"   

$`4`
NULL

$`5`
NULL

$`6`
NULL

右:第2行和第3行的错误计数器应加1。我们来做吧:

> apply(d, 1, function(x) if (as.numeric(x[["ratio"]]) > 1.00)
                          {x[["error.counter"]] <- x[["error.counter"]] + 1})
$`1`
NULL

$`2`
[1] 1

$`3`
[1] 1

$`4`
NULL

$`5`
NULL

$`6`
NULL

...并检查数据框中的结果:

> d
  ratio other error.counter
1  1.00     1             0
2  2.00     2             0
3  1.33     3             0
4  1.00     4             0
5  0.66     1             0
6  1.00     2             0

由于一个仍然逃避的原因,数据框未更新......

所以,2个问题:

  • 使用$引用列的问题是什么?
  • 为什么数据框没有更新?

2 个答案:

答案 0 :(得分:3)

通常,要获得变量之和到数据框中的某一点,您将使用累积和,即R中的函数cumsum。在这种情况下,您需要查找累积和如果ratio太大则为1的变量,否则为0。你可以这样做:

d$error.counter <- cumsum(d$ratio > 1)
d
#   ratio other error.counter
# 1  1.00     1             0
# 2  2.00     2             1
# 3  1.33     3             2
# 4  1.00     4             2
# 5  0.66     1             2
# 6  1.00     2             2

如果您只想在比率超过1时将error.counter设置为1,那么您只需删除cumsum

d$error.counter <- as.numeric(d$ratio > 1)
d
#   ratio other error.counter
# 1  1.00     1             0
# 2  2.00     2             1
# 3  1.33     3             1
# 4  1.00     4             0
# 5  0.66     1             0
# 6  1.00     2             0

如果你想将错误计数器设置为0,如果没有错误,否则积累它,或许:

d$error.counter <- ifelse(d$ratio > 1, cumsum(d$ratio > 1), 0)
d
#   ratio other error.counter
# 1  1.00     1             0
# 2  2.00     2             1
# 3  1.33     3             2
# 4  1.00     4             0
# 5  0.66     1             0
# 6  1.00     2             0

答案 1 :(得分:0)

ratio <- c(1.00, 2.00, 1.33, 1.00, 0.66, 1.00)
other <- c(1,2,3,4,1,2)
error.counter <- c(0,0,0,0,0,0)
df <- as.data.frame(cbind(ratio, other, error.counter))

df %>% mutate(error.counter = ifelse(ratio > 1, error.counter + 1, error.counter))

#   ratio other error.counter
# 1  1.00     1             0
# 2  2.00     2             1
# 3  1.33     3             1
# 4  1.00     4             0
# 5  0.66     1             0
# 6  1.00     2             0