使用mutate和逐行返回列表 [英] Return list using mutate and rowwise

查看:95
本文介绍了使用mutate和逐行返回列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用mutate和rowwise返回列表,但出现了代码中显示的错误.这些问题 Q1 Q2 有所帮助,但我想通过使用rowwise()遍历行和问题是3yr 7mth老.谢谢.

I'm trying to return a list using mutate and rowwise but get the error shown in the code. These questions Q1 Q2 helped, but I'd like to keep it simple by iterating over rows using rowwise(), and the questions are 3yr 7mth old. Thanks.

library(tidyverse)    
df <-  data.frame(Name=c("a","a","b","b","c"),X=c(1,2,3,4,5), Y=c(2,3,4,2,2))

    TestFn <- function(X,Y){
      Z <- list(X*5,Y/2,X+Y,X*2+5*Y)
      return (Z)
    }

    #this works
    SingleResult <- TestFn(5,20)

    #error - Error in mutate_impl(.data, dots) : incompatible size (4), expecting 1 (the group size) or 1
    dfResult <- df %>% 
      rowwise() %>% 
      mutate(R=TestFn(X,Y))

推荐答案

您的TestFn每行返回4个元素列表,该列表不能真正容纳在一行中.您可以先将返回的元素包装在向量中,以便返回的列表是单个元素列表:

Your TestFn returns a 4 elements list per row, which can't really be fit in a row; You can wrap the returned elements in a vector first so the returned list is a single element list:

TestFn <- function(X, Y) list(c(X*5, Y/2, X+Y, X*2+5*Y))
#                             ^ 
df %>% rowwise() %>% mutate(R=TestFn(X,Y)) %>% pull(R)
#[[1]]
#[1]  5  1  3 12

#[[2]]
#[1] 10.0  1.5  5.0 19.0

#[[3]]
#[1] 15  2  7 26

#[[4]]
#[1] 20  1  6 18

#[[5]]
#[1] 25  1  7 20


rowwise通常效率不高,如果要对解决方案进行矢量化处理,可以先计算四个表达式,然后转置结果:


rowwise is usually not as efficient, if you want to vectorize the solution, you can calculate the four expressions firstly and then transpose the result:

df$R = with(df, data.table::transpose(list(X*5, Y/2, X+Y, X*2+5*Y)))
df
#  Name X Y                    R
#1    a 1 2          5, 1, 3, 12
#2    a 2 3 10.0, 1.5, 5.0, 19.0
#3    b 3 4         15, 2, 7, 26
#4    b 4 2         20, 1, 6, 18
#5    c 5 2         25, 1, 7, 20

这篇关于使用mutate和逐行返回列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆