很抱歉,如果其他地方已经回答了这个问题,我确实找过了,但找不到可以复制的例子。
如果我有以下称为DF的数据帧,其中1-14是得分为1、0或3的项目
Id Date 1 2 3 4 5 6 7 8 9 10 11 12 13 14
1 01/01/01 1 0 3 3 1 0 1 3 1 0 3 0 1 1
2 01/02/01 0 3 1 1 0 1 1 1 1 3 1 1 1 3
我该如何创建一个列,为每个ID平均项目1-7,不包括3或0分(因此只有1个值(,然后为8-14创建另一个列?
所以我会有这个:
Id Date 1 2 3 4 5 6 7 8 9 10 11 12 13 14 av1-7 av8-14
1 01/01/01 1 0 3 3 1 0 1 3 1 0 3 0 1 1 0.428 0.428
2 01/02/01 0 3 1 1 0 1 1 1 1 3 1 1 1 3 0.57 0.71
如果有人能帮忙,我们将不胜感激。
以下是dplyr
:的方法
data %>%
rowwise() %>%
mutate(`av1-7` = mean(recode(c_across(`1`:`7`),`1`= 1, .default = 0)),
`av8-14` = mean(recode(c_across(`8`:`14`),`1`= 1, .default = 0)))
# Rowwise:
Id Date `1` `2` `3` `4` `5` `6` `7` `8` `9` `10` `11` `12` `13` `14` `av1-7` `av8-14`
<int> <chr> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <dbl> <dbl>
1 1 01/01/01 1 0 3 3 1 0 1 3 1 0 3 0 1 1 0.429 0.429
2 2 01/02/01 0 3 1 1 0 1 1 1 1 3 1 1 1 3 0.571 0.714
通常,将列名作为数字或包含-
不是一个好主意。因此,重命名这些列可能更好。
数据:
data <- structure(list(Id = 1:2, Date = c("01/01/01", "01/02/01"), `1` = 1:0,
`2` = c(0L, 3L), `3` = c(3L, 1L), `4` = c(3L, 1L), `5` = 1:0,
`6` = 0:1, `7` = c(1L, 1L), `8` = c(3L, 1L), `9` = c(1L,
1L), `10` = c(0L, 3L), `11` = c(3L, 1L), `12` = 0:1, `13` = c(1L,
1L), `14` = c(1L, 3L)), class = "data.frame", row.names = c(NA,
-2L))
我们可以通过select
对感兴趣的列使用rowMeans
df1 <- df1 %>%
mutate(across(`1`:`14`, ~ replace(., . != 1, 0))) %>%
transmute(`av1-7` = rowMeans(select(cur_data(), `1`:`7`), na.rm = TRUE),
`av8-14`= rowMeans(select(cur_data(), `8`:`14`), na.rm = TRUE)) %>%
bind_cols(df1, .) %>%
as_tibble
-输出
df1
# A tibble: 2 x 18
Id Date `1` `2` `3` `4` `5` `6` `7` `8` `9` `10` `11` `12` `13` `14` `av1-7` `av8-14`
<int> <chr> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <int> <dbl> <dbl>
1 1 01/01/01 1 0 3 3 1 0 1 3 1 0 3 0 1 1 0.429 0.429
2 2 01/02/01 0 3 1 1 0 1 1 1 1 3 1 1 1 3 0.571 0.714
数据
df1 <- structure(list(Id = 1:2, Date = c("01/01/01", "01/02/01"), `1` = 1:0,
`2` = c(0L, 3L), `3` = c(3L, 1L), `4` = c(3L, 1L), `5` = 1:0,
`6` = 0:1, `7` = c(1L, 1L), `8` = c(3L, 1L), `9` = c(1L,
1L), `10` = c(0L, 3L), `11` = c(3L, 1L), `12` = 0:1, `13` = c(1L,
1L), `14` = c(1L, 3L)), class = "data.frame", row.names = c(NA,
-2L))