将自定义函数应用于每一行仅使用参数的第一个值

问题描述 投票:5回答:4

我正在尝试使用以下数据集将NA值重新编码为列的子集中的0

set.seed(1)
df <- data.frame(
  id = c(1:10),
  trials = sample(1:3, 10, replace = T),
  t1 = c(sample(c(1:9, NA), 10)),
  t2 = c(sample(c(1:7, rep(NA, 3)), 10)),
  t3 = c(sample(c(1:5, rep(NA, 5)), 10))
  )

每行都有一定数量的试验(1-3之间),由trials专栏指定。列t1-t3代表每个试验的分数。

试验次数表明NAs应该被重新编码为0的列子集:NAs在试验次数内表示缺失数据,并且应该被重新编码为0,而NAs在试验次数之外没有意义,并且应该保持NAs。因此,对于一排trials == 3NA列中的t3将被重新编码为0,但连续trials == 2NA中的t3仍然是NA

所以,我尝试使用这个功能:

replace0 <- function(x, num.sun) {
  x[which(is.na(x[1:(num.sun + 2)]))] <- 0
  return(x)
}

这适用于单个矢量。当我尝试使用apply()将相同的函数应用于数据框时,尽管如此:

apply(df, 1, replace0, num.sun = df$trials)

我收到警告说:

In 1:(num.sun + 2) :
  numerical expression has 10 elements: only the first used

结果是num.sun不是让trials的值根据apply()中的值改变每一行,而是简单地使用trials列中的第一个值来表示每一行。我怎么能应用这个函数,以便num.sun参数根据df$trials的值改变?

谢谢!

编辑:正如一些人评论的那样,根据试验专栏,原始示例数据有一些非NA分数没有意义。这是一个更正的数据集:

df <- data.frame(
  id = c(1:5),
  trials = c(rep(1, 2), rep(2, 1), rep(3, 2)),
  t1 = c(NA, 7, NA, 6, NA),
  t2 = c(NA, NA, 3, 7, 12),
  t3 = c(NA, NA, NA, 4, NA)
)
r apply na missing-data
4个回答
2
投票

另一种方法:

# create an index of the NA values
w <- which(is.na(df), arr.ind = TRUE)

# create an index with the max column by row where an NA is allowed to be replaced by a zero
m <- matrix(c(1:nrow(df), (df$trials + 2)), ncol = 2)

# subset 'w' such that only the NA's which fall in the scope of 'm' remain
i <- w[w[,2] <= m[,2][match(w[,1], m[,1])],]

# use 'i' to replace the allowed NA's with a zero
df[i] <- 0

这使:

> df
   id trials t1 t2 t3
1   1      1  3 NA  5
2   2      2  2  2 NA
3   3      2  6  6  4
4   4      3  0  1  2
5   5      1  5 NA NA
6   6      3  7  0  0
7   7      3  8  7  0
8   8      2  4  5  1
9   9      2  1  3 NA
10 10      1  9  4  3

您可以轻松地将其包装在一个函数中:

replace.NA.with.0 <- function(df) {
  w <- which(is.na(df), arr.ind = TRUE)
  m <- matrix(c(1:nrow(df), (df$trials + 2)), ncol = 2)
  i <- w[w[,2] <= m[,2][match(w[,1], m[,1])],]
  df[i] <- 0
  return(df)
}

现在,使用replace.NA.with.0(df)将产生上述结果。


正如其他人所指出的,某些行(1,3和10)具有比路径更多的值。您可以通过将上述函数重写为以下内容来解决该问题:

replace.with.NA.or.0 <- function(df) {
  w <- which(is.na(df), arr.ind = TRUE)
  df[w] <- 0

  v <- tapply(m[,2], m[,1], FUN = function(x) tail(x:5,-1))
  ina <- matrix(as.integer(unlist(stack(v)[2:1])), ncol = 2)
  df[ina] <- NA

  return(df)
}

现在,使用replace.with.NA.or.0(df)会产生以下结果:

   id trials t1 t2 t3
1   1      1  3 NA NA
2   2      2  2  2 NA
3   3      2  6  6 NA
4   4      3  0  1  2
5   5      1  5 NA NA
6   6      3  7  0  0
7   7      3  8  7  0
8   8      2  4  5 NA
9   9      2  1  3 NA
10 10      1  9 NA NA

1
投票

在这里,我只使用双子集x[paste0('t',x['trials'])]重写你的函数,它克服了第6行的其他两个解决方案中的问题

replace0 <- function(x){
         #browser()
         x_na <- x[paste0('t',x['trials'])]
         if(is.na(x_na)){x[paste0('t',x['trials'])] <- 0}
     return(x)
}

t(apply(df, 1, replace0))

     id trials t1 t2 t3
[1,]  1      1  3 NA  5
[2,]  2      2  2  2 NA
[3,]  3      2  6  6  4
[4,]  4      3 NA  1  2
[5,]  5      1  5 NA NA
[6,]  6      3  7 NA  0
[7,]  7      3  8  7  0
[8,]  8      2  4  5  1
[9,]  9      2  1  3 NA
[10,] 10      1  9  4  3

1
投票

这是一种方法:

x <- is.na(df)
df[x & t(apply(x, 1, cumsum)) > 3 - df$trials] <- 0

输出如下所示:

> df
   id trials t1 t2 t3
1   1      1  3 NA  5
2   2      2  2  2 NA
3   3      2  6  6  4
4   4      3  0  1  2
5   5      1  5 NA NA
6   6      3  7  0  0
7   7      3  8  7  0
8   8      2  4  5  1
9   9      2  1  3 NA
10 10      1  9  4  3
> x <- is.na(df)
> df[x & t(apply(x, 1, cumsum)) > 3 - df$trials] <- 0
> df
   id trials t1 t2 t3
1   1      1  3 NA  5
2   2      2  2  2 NA
3   3      2  6  6  4
4   4      3  0  1  2
5   5      1  5 NA NA
6   6      3  7  0  0
7   7      3  8  7  0
8   8      2  4  5  1
9   9      2  1  3 NA
10 10      1  9  4  3

注意:第1/3/10行是有问题的,因为非NA值比试验更多。


0
投票

这是一种tidyverse方式,请注意它不会提供与其他解决方案相同的输出。

您的示例数据显示“未发生”的试验结果,我假设您的实际数据没有。

library(tidyverse)
df %>%
  nest(matches("^t\\d")) %>%
  mutate(data = map2(data,trials,~mutate_all(.,replace_na,0) %>% select(.,1:.y))) %>%
  unnest

#    id trials t1 t2 t3
# 1   1      1  3 NA NA
# 2   2      2  2  2 NA
# 3   3      2  6  6 NA
# 4   4      3  0  1  2
# 5   5      1  5 NA NA
# 6   6      3  7  0  0
# 7   7      3  8  7  0
# 8   8      2  4  5 NA
# 9   9      2  1  3 NA
# 10 10      1  9 NA NA

使用更常用的gather策略,这将是:

df %>%
  gather(k,v,matches("^t\\d")) %>%
  arrange(id) %>%
  group_by(id) %>%
  slice(1:first(trials)) %>%
  mutate_at("v",~replace(.,is.na(.),0)) %>%
  spread(k,v)

# # A tibble: 10 x 5
# # Groups:   id [10]
#       id trials    t1    t2    t3
#    <int>  <int> <dbl> <dbl> <dbl>
#  1     1      1     3    NA    NA
#  2     2      2     2     2    NA
#  3     3      2     6     6    NA
#  4     4      3     0     1     2
#  5     5      1     5    NA    NA
#  6     6      3     7     0     0
#  7     7      3     8     7     0
#  8     8      2     4     5    NA
#  9     9      2     1     3    NA
# 10    10      1     9    NA    NA
© www.soinside.com 2019 - 2024. All rights reserved.