很抱歉,如果这个问题已经在其他地方得到了回答,我确实看过了,但是找不到一个我可以复制的例子。
如果我有以下数据框架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 (不包括3分或0分)平均项1-7 (所以只有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
如果有人能帮忙的话,我会非常感激的。
发布于 2021-06-09 18:07:19
下面是一种使用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))
发布于 2021-06-09 18:07:34
我们可以通过对感兴趣的列进行rowMeans
来使用select
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
-output
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))
https://stackoverflow.com/questions/67909467
复制相似问题