循环和条件语句
使用循环和条件语句,我想确定有超过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))
}
}
这不是工作,以及如何保存这两个“产品”和“存储”作为单独的载体?
不需要明确的for循环。
这是一个单独保存列store
和product
,为此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))
您不需要使用'which':'df [df $ cost> 2.5,'store']'给出与'df [其中(df $ cost> 2.5),“store”]' – HubertL
是相同的结果。但它也没有伤害。在我看来,回归指数对于更复杂的过滤具有优势,并且我认为它是好的(更好的)实践。见例如讨论[这里](https://stackoverflow.com/questions/6918657/whats-the-use-of-which)。 –
你可以做它输出你感兴趣的字符串矢量如下:我不知道为什么要保存
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"
谢谢。这工作! 这是可行的一个for循环,如果条件语句? –
是的,但是当不使用'for'循环时,这些操作通常更高效,更易读。为了将来的需要,你可能想看看'dplyr'(实际上'tidyverse')和/或'data.table';这些都非常有效,避免了大多数for循环的需要。这些对于这个问题来说并不是必要的。 – steveb
,但你可以做这样的事情。
df <- df[df$cost > 2.50,]
cat(paste0(df$customer, " purchased ", df$product,
" at ",df$store, " for ", cost, "./n"))
为什么你需要保存它们? – Elin