如何设置;空(空)";在函数R中为0

如何设置;空(空)";在函数R中为0,r,R,我一直在写一个函数来处理sales,有时候这个方法没有sales,所以R返回null(空),我怎么能将它设置为零?因为我将在列表中使用该值,然后在矩阵中与其他列表一起使用,如果列表不够长,它将再次启动列表,并将弄乱我的仪表板。例如: s1<- c("sales_method1", "sales_method3") s2<- c(50, 100) df<-data.frame(s1, s2) my_function <- function(df){ breakdown_

我一直在写一个函数来处理sales,有时候这个方法没有sales,所以R返回null(空),我怎么能将它设置为零?因为我将在列表中使用该值,然后在矩阵中与其他列表一起使用,如果列表不够长,它将再次启动列表,并将弄乱我的仪表板。例如:

s1<- c("sales_method1", "sales_method3")
s2<- c(50, 100)
df<-data.frame(s1, s2)

my_function <- function(df){

breakdown_of_sales <- lapply(split(df$s2, df$s1), sum)

sales_method1 <- breakdown_of_sales$sales_method1
sales_method2 <- breakdown_of_sales$sales_method2
sales_method3 <- breakdown_of_sales$sales_method3

list <- c(sales_method1, sales_method2, sales_method3)

Pot  <<- matrix(`list`,
               nrow = 1,
               ncol = 3)
}

s1我不确定这是不是你想要的。然而,我尝试了它并成功了

s1<- c("sales_method1", "sales_method3")
s2<- c(50, 100)
df<-data.frame(s1, s2)

my_function <- function(df){

    breakdown_of_sales <- lapply(split(df$s2, df$s1), sum)

    sales_method1 <- breakdown_of_sales$sales_method1
    sales_method2 <- breakdown_of_sales$sales_method2
    sales_method3 <- breakdown_of_sales$sales_method3
    sales_method <- list(sales_method1, sales_method2, sales_method3)
    for(i in 1:length(sales_method)){
        if (any(is.null(sales_method[[i]]))){
            sales_method[[i]] <- 0
        }
    }


    list <- sales_method



    Pot  <<- matrix(`list`,
                    nrow = 1,
                    ncol = 3)
}

s1add
return(0)
在您的
list@JRR之后的代码中的好位置处添加
return(0)
?我不理解文件。我试着在sales_method2@Benjamin
列表之后添加它,我已经在本例和实际代码中对它进行了排序。谢谢你,本杰明@Alice我知道没有关于
sales\u method2
的数据,这就是整个问题所在。这就是我想要的,我最后使用了'sales\u method2
for
循环很多列表或向量元素是很好的。使用一种方法让你比重复你的代码更容易,这是很好的。我将把它添加到要学习的内容列表中,谢谢。我也给你打了个勾,还加了个记号:)
s1<- c("sales_method1", "sales_method3")
s2<- c(50, 100)
df<-data.frame(s1, s2)

my_function <- function(df){

    breakdown_of_sales <- lapply(split(df$s2, df$s1), sum)

    sales_method1 <- breakdown_of_sales$sales_method1
    sales_method2 <- breakdown_of_sales$sales_method2
    sales_method3 <- breakdown_of_sales$sales_method3
    sales_method <- list(sales_method1, sales_method2, sales_method3)
    for(i in 1:length(sales_method)){
        if (any(is.null(sales_method[[i]]))){
            sales_method[[i]] <- 0
        }
    }


    list <- sales_method



    Pot  <<- matrix(`list`,
                    nrow = 1,
                    ncol = 3)
}