2017-11-27 33 views
0

私は売上を扱う関数を書いていますが、そのメソッドの売上がないのでRはnull(空)を返します。ゼロ?そのリストの値をリスト内で使用し、リストが他のリストと並んでいる場合は、リストの長さが長くない場合は、リストを再び開始してダッシュボードを駄目にします。例:関数内で "NULL(空)"を0に設定する方法R

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) 
} 

これは、私はそれがnullであるとき、それは0に等しくなるようにデフォルトにしたいとき、私の鍋にそれを作る、50,100,50を含有させること、50、100、50

sales_method2 <- breakdown_of_sales$sales_method2 

として戻っヌルを返します。 50,0,100

+0

'(0)' 'あなたのリスト<後のあなたのコード – JRR

+0

で良い場所でリターンを追加 - '呼び出し、使用 '場合(is.null(リスト))リスト< - 0 ' – Benjamin

+0

@JRRそうだろうか?私はドキュメントを理解していません。私はsales_method2 < - breakdown_of_sales $ sales_method2の直後にそれを追加しようとしましたが、出力を変更していませんでした。また、return((method2 < - breakdown_of_sales $ sales_method2)、0)を試みましたが、エラーを投げました –

答えて

1

これはあなたが望むかどうかわかりません。しかし、私はそれを試して働いた。

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) 
} 
+0

うん、それは私が' sales_method2 < - breakdown_of_sales $ sales_method2を使用して終わってしまいました(if.null(sales_method2)){ sales_method2 < - 0}。私はまだ完全にループを理解していませんし、私のプログラムでも20以上のメソッドがあり、2つしか見つからなかったのです。 –

+0

'for'ループは多くのリストまたはベクトル要素をループするのに適しています。あなたのコードを繰り返すよりも簡単にするための方法を使用することは良いことです。 – Alice

+1

私はそれを感謝するために物事のリストに追加します。私はまた、あなたを尋ねてupdppyed :) –

関連する問題