使用循环和条件语句,我想识别值大于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美元的购物并保存&#34;商店&#34;和&#34;产品&#34;作为与超过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))
}
}
这不适用于工作,如何保存两个&#34;产品&#34;和&#34;存储&#34;作为单独的载体?
答案 0 :(得分:0)
不需要明确的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))
答案 1 :(得分: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"
答案 2 :(得分:0)
我不确定你为什么要保存,但你可以这样做。
df <- df[df$cost > 2.50,]
cat(paste0(df$customer, " purchased ", df$product,
" at ",df$store, " for ", cost, "./n"))