2017-10-10 196 views
0

使用循環和條件語句,我想確定有超過2.50循環和條件語句

customer <- c("john", "amy", "doug") 
product <- c("coffee", "pastry", "pastry") 
store <- c("a", "b", "c") 
cost  <- c(5.50, 2.45, 3.00) 

df <- data.frame(customer, product, store, cost) 

的值,我想找出超過$ 2.50購買並保存「存儲」和「產品」作爲行與這些購買相關的獨立媒介超過2.50美元。

到目前爲止,這是我的代碼,它是不工作...

for (row in 1:nrow(df)) { 
    customer <- df[row, "customer"] 
    product <- df[row, "product"] 
    store <- df[row, "store"] 
    cost <- df[row, "cost"] 

    if(cost > 2.50) { 
     print(paste(customer, "purchased", product, "at", store, "for", cost)) 
    } 
} 

這不是工作,以及如何保存這兩個「產品」和「存儲」作爲單獨的載體?

+0

爲什麼你需要保存它們? – Elin

回答

0

不需要明確的for循環。

這是一個單獨保存列storeproduct,爲此cost > 2.5

store.sel <- df[which(df$cost > 2.5), "store"] 
product.sel <- df[which(df$cost > 2.5), "product"] 

或子集的dataframe

subset(df, cost > 2.5) 

,然後選擇所需的列

with(subset(df, cost > 2.5), paste(customer, "purchased", product, "at", store, "for", cost)) 
+0

您不需要使用'which':'df [df $ cost> 2.5,'store']'給出與'df [其中(df $ cost> 2.5),「store」]' – HubertL

+0

是相同的結果。但它也沒有傷害。在我看來,迴歸指數對於更復雜的過濾具有優勢,並且我認爲它是好的(更好的)實踐。見例如討論[這裏](https://stackoverflow.com/questions/6918657/whats-the-use-of-which)。 –

0

你可以做它輸出你感興趣的字符串矢量如下:我不知道爲什麼要保存

df2 <- df[df$cost > 2.5,] 
with(df2, paste(customer, "purchased", product, "at", store, "for", cost)) 

## [1] "john purchased coffee at a for 5.5" "doug purchased pastry at c for 3" 
+0

謝謝。這工作! 這是可行的一個for循環,如果條件語句? –

+0

是的,但是當不使用'for'循環時,這些操作通常更高效,更易讀。爲了將來的需要,你可能想看看'dplyr'(實際上'tidyverse')和/或'data.table';這些都非常有效,避免了大多數for循環的需要。這些對於這個問題來說並不是必要的。 – steveb

0

,但你可以做這樣的事情。

df <- df[df$cost > 2.50,] 
    cat(paste0(df$customer, " purchased ", df$product, 
     " at ",df$store, " for ", cost, "./n"))