如何在R中的数据帧中使用“ for循环”

时间:2020-01-07 06:11:03

标签: r loops

我正在尝试使用for循环计算中国和美国位置的总价:

请参考下面的示例数据框和代码:

z <- data.frame(location = c("china", "china", "US", "US" ), quantity = c(100, 200, 100, 200))

## Calculate Total price, considering price for one quanity is $1 for china and $3 for US

for row in 1:nrow(z) {

  l <- z[row, "location"]

  q <- z[row, "quanity"]

  ifelse (l == "china", 

          z$total <- (z$quantity * 1),

          z$total <- (z$quantity * 3)) 

4 个答案:

答案 0 :(得分:3)

在R中,大多数时候您可以无循环执行。如果仅显示2个位置,则在这种情况下,您也可以使用ifelse。试试

transform(z, total = quantity * c(1, 3)[(location != "china") + 1])

#  location quantity total
#1    china      100   100
#2    china      200   200
#3       US      100   300
#4       US      200   600

如果您有多个这样的国家/地区,则也可以使用case_when中的dplyr

library(dplyr)
z %>%
  mutate(total = case_when(location == "china"~quantity, 
                           location == "US"~quantity * 3, 
                           ....more countries))

答案 1 :(得分:2)

您根本不需要循环

library(dplyr)

z <- data.frame(location = c("china", "china", "US", "US" ),
                quantity = c(100, 200, 100, 200))


z %>% group_by(location) %>%
  summarise(sum_quantity = quantity %>% sum) %>% 
  mutate(total = if_else(location == 'china',
                                sum_quantity,
                                sum_quantity * 3))
#> # A tibble: 2 x 3
#>   location sum_quantity total
#>   <fct>           <dbl> <dbl>
#> 1 china             300   300
#> 2 US                300   900


# the ideal world

new_z <- data.frame(location = c("china", "china", "US", "US" ),
                quantity = c(100, 200, 100, 200),
                value_rate = c(1,1,3,3))

new_z %>% group_by(location) %>%
  summarise(sum_quantity = (quantity * value_rate) %>% sum)
#> # A tibble: 2 x 2
#>   location sum_quantity
#>   <fct>           <dbl>
#> 1 china             300
#> 2 US                900

reprex package(v0.3.0)于2020-01-07创建

答案 2 :(得分:1)

我确实同意其他答案,在这种特殊情况下,for循环可能是一个过大的杀伤力,下面是我尝试为您提供一个整洁的解决方案。但是,如果您确实想遵循循环范例,请查看For each row in an R dataframe

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(magrittr)
z <- data.frame(location = c("china", "china", "US", "US" ), quantity = c(100, 200, 100, 200))
z %>% 
  mutate(price = ifelse(location == "china", 1, 3)) %>% 
  group_by(location) %>% 
  summarise(total = sum(quantity * price))
#> # A tibble: 2 x 2
#>   location total
#>   <fct>    <dbl>
#> 1 china      300
#> 2 US         900

reprex package(v0.3.0.9000)于2020-01-07创建

答案 3 :(得分:1)

另一种基本的R解决方案是使用ifelse,如下所示:

z <- within(z,total <- quantity*ifelse(location=="china",1,3))

这样

> z
  location quantity total
1    china      100   100
2    china      200   200
3       US      100   300
4       US      200   600