1

我想用dplyrR 包进行逐行计算。计算的结果是一个系列。然后我想用计算的系列替换整行。这是代码:

df <- tibble(id = 1:6, w = 10:15, x = 20:25, y = 30:35, z = 40:45)

我想运行isoreg结果是一个系列,然后用 w:z 列下的内容替换它:

df %>% rowwise %>%
  mutate(across(c_across(w:z), ~ isoreg(as.numeric(c_across(w:z)))$yf))

似乎此方法仅用于替换一个元素,而不是整行。这isoreg只是一个示例函数,我们可以使用其他函数返回一系列而不是单个值作为输出。

4

2 回答 2

1

我们可以pmap使用unnest_wider

library(dplyr)
library(tidyr)
library(purrr)
df %>% 
   mutate(new = pmap(select(., w:z), ~ isoreg(c(...))$yf)) %>% 
   unnest_wider(c(new))
# A tibble: 6 x 9
#     id     w     x     y     z  ...1  ...2  ...3  ...4
#  <int> <int> <int> <int> <int> <dbl> <dbl> <dbl> <dbl>
#1     1    10    20    30    40    10    20    30    40
#2     2    11    21    31    41    11    21    31    41
#3     3    12    22    32    42    12    22    32    42
#4     4    13    23    33    43    13    23    33    43
#5     5    14    24    34    44    14    24    34    44
#6     6    15    25    35    45    15    25    35    45
于 2020-07-02T19:53:21.593 回答
1

您也不需要across使用c_across. 对于逐行操作,仅使用c_across. 还c_across需要一个汇总值作为输出,因此您不能一次性替换所有行。hack 是捕获列表中的所有值,并用于unnest_wider将这些值作为单独的列获取。

library(dplyr)
df %>% 
  rowwise() %>%
  mutate(output = list(isoreg(c_across(w:z))$yf)) %>%
  tidyr::unnest_wider(output)


#     id     w     x     y     z  ...1  ...2  ...3  ...4
#  <int> <int> <int> <int> <int> <dbl> <dbl> <dbl> <dbl>
#1     1    10    20    30    40    10    20    30    40
#2     2    11    21    31    41    11    21    31    41
#3     3    12    22    32    42    12    22    32    42
#4     4    13    23    33    43    13    23    33    43
#5     5    14    24    34    44    14    24    34    44
#6     6    15    25    35    45    15    25    35    45

由于isoregis not named的输出unnest_wider给出的名称为..1..2。如果需要,您可以重命名它们并删除不需要的列。


Base R 选项是使用apply

df[-1] <- t(apply(df[-1], 1, function(x) isoreg(x)$yf))
于 2020-07-02T10:21:54.170 回答